简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM