Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript .forEach() doesn't work for DOM nodes because they change in the process [duplicate]

I have the following buggy code to move all DOM elements from one node to another:

div.childNodes.forEach((n) => me.container.appendChild(n));

Unfortunately, this copies only half of the nodes. The reason for this seems to be that internally, javascript is counting like in a standard for loop:

for(let i = 0; i < div.childNodes.length; i++) {
    me.container.appendChild(div.childNodes[i]);
}

This causes the behavior because div.childNodes.length decreases each time one of its items is appended to me.container.

The following construction also suffers the same problem:

for (const n of div.childNodes) {
    me.container.appendChild(n);
}

The question here is, what is the best practice to do this and avoid such bugs? Should we trust javascript's functional functions to actually do what they describe?

I have found two candidates that work, and I wonder if there is a noticable speed difference because I prefer this first one due to it seeming simpler:

Array.from(div.childNodes).forEach((n) => me.container.appendChild(n));

And without converting:

for (let i = div.childNodes.length; i > 0; i--) {
    me.container.appendChild(div.childNodes[0]);
}

Both of these examples do work and copy all the nodes.

like image 524
Jeroen van de Ven Avatar asked May 22 '18 09:05

Jeroen van de Ven


Video Answer


1 Answers

How about

while (div.hasChildNodes()) { me.container.appendChild(div.firstChild)}
like image 74
visibleman Avatar answered Oct 14 '22 02:10

visibleman