0

I have a svg as below:

<g id="proyectoActual"> 
        <g id="BORDE">
            <g id="foo"/>
        </g>

        <g id="FASES">  
            <g id="foo"/>       
        </g>

        <g id="TEXTO">  
            <g id="foo"/>
        </g>

        <g id="PROTECCIONES">
            <g id="foo"/>
        </g>

        <g id="LINEAS">
            <g id="foo"/>
        </g>

        <g id="BOLAS">
            <g id="foo"/>
        </g>
    </g>
</g>

I clone this tree with

var nodoClonado=gRootDibujo.cloneNode(true);

Consulting its children and its children number, it's OK.

When I try to add the nodes to another SVG with...

for (var i=1;i<nodoClonado.childNodes.length;i++)
    contenedorBounder.appendChild (nodoClonado.childNodes[i]);

It seems only add 1, 3, 5.. (odd nodes "FASES", PROTECCIONES" and "BOLAS").

If I change var i=2, only add 2, 4, 6 (odd nodes).

What have I done wrong?

Thanks in advance

Frank T
  • 8,268
  • 8
  • 50
  • 67
Javier
  • 189
  • 3
  • 16

2 Answers2

2

When you append the node to some other element, the node is no longer a child of its original parent, since it has been moved to the new location in the DOM. So after you move childNodes[0], the node that previously was in childNodes[1] moves to [0], [2] moves to [1], etc. When i increments to 1, it moves childNodes[1], which was the original [2]. So you've skipped the original [1] node. This happens for each child, so you end up copying only the original even children.

Instead of a for loop, you can do:

while (nodoClonado.childNodes.length > 0) {
    contenedorBounder.appendChild (nodoClonado.childNodes[0]);
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

As Ram pointed out in his comment, you need to clone the node first. Just adding the node 'moves' the node to the new parent and detaches from the previous parent.

This should do the trick:

for (var i=0;i<nodoClonado.childNodes.length;i++)
    contenedorBounder.appendChild (nodoClonado.childNodes[i].cloneNode(true));
Charlie
  • 8,530
  • 2
  • 55
  • 53
  • Another option is converting the `.childNodes` collection into an array: https://stackoverflow.com/questions/2735067/how-to-convert-a-dom-node-list-to-an-array-in-javascript – Ram Aug 16 '17 at 20:49