Connor Atherton
Connor Atherton

Reputation: 161

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

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!

Upvotes: 0

Views: 971

Answers (2)

Bergi
Bergi

Reputation: 664444

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);
}

Upvotes: 1

Paul S.
Paul S.

Reputation: 66324

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());

Upvotes: 1

Related Questions