Quaxton Hale Quaxton Hale - 11 days ago 5
HTML Question

Changing the color of individual characters in an SVG text element

Is it possible to change the color of individual characters of an SVG

<text>
element? For example, in the following sample text, I want the character
5
to be green, and the character
6
to be red.

word = "{5,6}"
tspan.document.createElementNS(namespace,"tspan");
tspan.textContent = word;

//tspan.setAttributeNS(null,"fill","green");
textNode.appendChild(tspan);

Answer

You can use setAttribute instead of setAttributeNS to set the color.

For example:

<script>
  var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
  svg.setAttribute('style', 'border: 0px solid black');
  svg.setAttribute('width', '600');
  svg.setAttribute('height', '250');

  //Text
  var newText = document.createElementNS("http://www.w3.org/2000/svg","text");
  newText.setAttributeNS(null,"x",20);      
  newText.setAttributeNS(null,"y",100);   
  newText.setAttribute('style', 'font-size:24px');

  //Text span
  var txtSpan1 = document.createElementNS("http://www.w3.org/2000/svg","tspan");
  txtSpan1.textContent = "Eins";
  newText.appendChild(txtSpan1);

  //Text span with color
  var txtSpan2 = document.createElementNS("http://www.w3.org/2000/svg","tspan");
  txtSpan2.textContent = "t";
  txtSpan2.setAttribute('style', 'fill:green');
  newText.appendChild(txtSpan2);

  //Text span without color
  var txtSpan3 = document.createElementNS("http://www.w3.org/2000/svg","tspan");
  txtSpan3.textContent = "e";
  newText.appendChild(txtSpan3);
  var txtSpan4 = document.createElementNS("http://www.w3.org/2000/svg","tspan");

  svg.appendChild(newText);
  document.body.appendChild(svg);

</script>

jsFiddle for another way to do the text coloring using innerHTML property of text element.

Comments