3

I'm not sure of the best way to ask this. I am wanting to append multiple tspan child elements to a single svg text object. I have the following code.

var tspanElement = document.createElementNS("http://www.w3.org/2000/svg", "tspan");
var majNote1 = document.getElementById('majNote1');

function myFunction() {
 for(i=1;i<6;i++){
   tspanElement.textContent=i;
   tspanElement.setAttribute("id",i);
   majNote1.appendChild(tspanElement);
 }   
}

When I run this, It appears that the tspan element is appended only once and not 5 times. Is it possible to reuse the same tspan variable and append it 5 separate times?

You can see an example at http://codepen.io/cmgdesignstudios/pen/VePwog?editors=101

Christopher Gaston
  • 491
  • 2
  • 6
  • 18

1 Answers1

5

First appendChild adds the element to the document. Subsequent calls of appendChild on the same element only move the element in the document tree. In your case, tspanElement is already the last child of majNote1, so appendChild does nothing.

So, yes, you should explicitly create each element. But you can and probably should reuse the variable: it is simply a named reference to the object, so you just move the createElementNS line to the top of the loop body, and the variable will refer to a different element on each iteration:

function myFunction() {
  var majNote1 = document.getElementById('majNote1');
  var tspanElement;
  for(i=1;i<6;i++){
    tspanElement = document.createElementNS("http://www.w3.org/2000/svg", "tspan");
    tspanElement.textContent=i;
    tspanElement.setAttribute("id",i);
    majNote1.appendChild(tspanElement);
  }   
}
Sergey Salnikov
  • 321
  • 1
  • 5