Looping through an array of nodes and appending a child to each one only appends to the last element

StackOverflow https://stackoverflow.com/questions/18116613

  •  23-06-2022
  •  | 
  •  

Question

I want to loop through an array of nodes referring to SVG elements and append a text element to each one but for some reason all of the text only appears in the last SVG element in the array.

Here's the code

var svgs = document.getElementsByTagName('svg');

var moduleNames = ["1", "2", "3", "4", "5"];
var textEl = document.createElementNS(svgns, 'text');

var i = 1;

while(i < moduleNames.length) {

  textNode = document.createTextNode( moduleNames[i] );
  textEl.appendChild(textNode);
  svgs[i].appendChild(textEl);

  i++;

}

Oh, and before I do this I already know the number of SVG elements will be the same length as the moduleNames array.

Thanks!

Was it helpful?

Solution

text only appears in the last SVG element

Not in the last svg <text> element, but in the only one. You're creating a single element and keep appending text nodes to it. Appending the same element to different parents doesn't clone it, but only move it.

You probably want to create multiple elements:

var moduleNames = ["1", "2", "3", "4", "5"];
for (var i=0; i < moduleNames.length; i++) {
    var textEl = document.createElementNS(svgns, 'text'),
        textNode = document.createTextNode( moduleNames[i] );
    textEl.appendChild(textNode);
    svgs[i].appendChild(textEl);
}

OTHER TIPS

It looks like you want to append a new element to each SVG, but you're just moving one across them all, so it ends up on the last one. The easiest way to create new copies of an element is with cloneNode

svgs[i].appendChild(textEl.cloneNode());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top