将 childNodes 移动到其他 parent 只影响一半

Move childNodes to other parent affect only half of them

我尝试使用 NodeList.forEach() 将所有子节点从一个 parent 移动到另一个,但这只适用于其中的一半。

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

您可以在这里尝试一下: https://jsfiddle.net/t4g0vje2/3/

我想知道:为什么会这样?移动所有 children 的最佳解决方案是什么?

似乎每次

都从 parent.childNodes 中删除子节点
child => newParent.appendChild(child)

正在执行中。所以你遇到了问题,因为每次执行上面的行时你的集合都会被修改。

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

会成功,因为您首先要创建一个包含 10 个元素的新数组,然后遍历所有 10 个项目

我 运行 我的代码也遇到了这个完全相同的问题。我正在做以下事情:

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

我修复它的方法是删除 removeChild 行,因此它看起来像这样:

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

解决了问题。 Firefox 做同样的事情。我在以下链接找到了原因:

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

这篇文章的重点是:

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.

当你想到它时,它是有道理的。此行为记录在 w3schools 网站上,但很容易被忽视。