Search code examples
javascripthtmlnodelist

Move childNodes to other parent affect only half of them


I try to move all childNodes from one parent to an other using NodeList.forEach() but this works only for the half of them.

parent.childNodes.forEach(child => newParent.appendChild(child))

you can try yourself here: https://jsfiddle.net/t4g0vje2/3/

I want to know: Why this is happening? What's your best solution moving all children?


Solution

  • It seems that child node is being removed from parent.childNodes each time

    child => newParent.appendChild(child)
    

    is being executed. So you are having a problem since your collection is being modified each time the line above is executed.

    Array.from(parent.childNodes).forEach(child => newParent.appendChild(child))
    

    will do the trick, since you are first creating a new array of 10 elements, and traversing through all of the 10 items