Skip to content
TheChatArchiveThe Chat Archive
gpt-4.1-2025-04-14· OpenAIHugging Face LMArena Human Preference 140K

How to change the color of an SVG text?

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with o4-mini-2025-04-16’s answer.
  1. User

    How to change the color of an SVG text?

  2. Assistant

    To change the color of an SVG <text> element using JavaScript, you can modify its fill attribute or its CSS style. The fill property controls the color of the text in SVG.

    Here are a few ways to do it:


    1. Directly Set the fill Attribute

    <svg width="200" height="100">
      <text id="myText" x="10" y="50" fill="black">Hello SVG</text>
    </svg>
    
    const textElement = document.getElementById('myText');
    textElement.setAttribute('fill', 'red'); // Changes text color to red
    

    2. Use the style Property

    textElement.style.fill = 'blue'; // Changes text color to blue
    

    3. Using CSS Classes

    You can also define a CSS class and toggle it with JavaScript:

    <style>
      .highlight {
        fill: orange;
      }
    </style>
    <svg width="200" height="100">
      <text id="myText" x="10" y="50">Hello SVG</text>
    </svg>
    
    textElement.classList.add('highlight'); // Applies the orange color
    

    Summary Table

    MethodExample Code
    setAttributetextElement.setAttribute('fill', 'red');
    style propertytextElement.style.fill = 'blue';
    CSS classtextElement.classList.add('highlight');

    Note:

    • The color property does not affect SVG text color; use fill instead.
    • You can use any valid CSS color value (e.g., "red", "#ff0000", "rgb(255,0,0)").

    Let me know if you need a full working example!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.