gpt-4.1-2025-04-14· OpenAI
LMArena Human Preference 140K
How to change the color of an SVG text?
- User
How to change the color of an SVG text?
- Assistant
To change the color of an SVG
<text>element using JavaScript, you can modify itsfillattribute or its CSSstyle. Thefillproperty controls the color of the text in SVG.Here are a few ways to do it:
1. Directly Set the
fillAttribute<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
stylePropertytextElement.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
Method Example Code setAttributetextElement.setAttribute('fill', 'red');stylepropertytextElement.style.fill = 'blue';CSS class textElement.classList.add('highlight');
Note:
- The
colorproperty does not affect SVG text color; usefillinstead. - 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!
- The
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.