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.
How about
while (div.hasChildNodes()) { me.container.appendChild(div.firstChild)}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With