0

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?

Buntel
  • 540
  • 6
  • 19

2 Answers2

3

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

M. Duisenbayev
  • 309
  • 1
  • 4
1

I have ran into this exact same problem with my code as well. I was doing the following:

while (shadowObject.firstChild) {
    parentObject.appendChild(shadowObject.firstChild);
    shadowObject.removeChild(shadowObject.firstChild);
}

The way that I fixed it was to remove the removeChild line so it looks like this:

while (shadowObject.firstChild) {
    parentObject.appendChild(shadowObject.firstChild);
}

which fixed the problem. Firefox does the same thing. I found the reason for it at the following links:

https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild

The critical point of this article is this:

The Node.appendChild() method adds a node to the end of the list of children of a specified parent node. If the given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new position (there is no requirement to remove the node from its parent node before appending it to some other node).

This means that a node can't be in two points of the document simultaneously. So if the node already has a parent, the node is first removed, then appended at the new position.

When you think about it, it makes sense. This behavior is documented on the w3schools site, but it's easy to overlook.

Daniel Rudy
  • 1,411
  • 12
  • 23