kanok ja
kanok ja

Reputation: 21

How to change value of SVG text?

I have a svg texts array:

var texts = []; //for svg text objects

function create() {
  for(var i=0; i<6; i++) {
     var d = 10;
     var n = d-1;
     var text = document.createElementNS(NS, 'text'); 
     var data = document.createTextNode(d); 
     text.setAttributeNS(null, "id", "text"+i); 
     texts.push(text);
     var t = texts[i];
     document.getElementById('svgOne').appendChild(t); 
     change(n);
     d--;
  }
}

function change(n) {
   //change 
}

how to change value of text "d" -> "n"?
I use already node.nodeValue but doesn't working.

 t.firstChild.value = n;

i don't want use another js library.
Is there simple way to change value?

Upvotes: 1

Views: 6839

Answers (1)

Bobby Orndorff
Bobby Orndorff

Reputation: 3335

To change the text displayed in a SVG text element, you can set the nodeValue of the child text node of the SVG text element. For example...

var svgTextElement = document.getElementById("text1");
var textNode = svgTextElement.childNodes[0];
textNode.nodeValue = "New text.";

Note that your code was not adding the text node to the svg text element. You need to call appendChild() method. For example...

var text = document.createElementNS(NS, 'text'); 
var data = document.createTextNode(d);
text.appendChild(data);

Upvotes: 2

Related Questions