Javier Javier - 10 months ago 35
Javascript Question

Curious javascript parsing, only returns even nodes.: What I'm doing wrong in this code?

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

Answer Source

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));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download