Categories
JavaScript Answers

How to move all HTML element children to another parent using JavaScript?

Spread the love

Sometimes, we want to move all HTML element children to another parent using JavaScript.

In this article, we’ll look at how to move all HTML element children to another parent using JavaScript.

How to move all HTML element children to another parent using JavaScript?

To move all HTML element children to another parent using JavaScript, we can use the appendChild method.

For instance, we write

const setParent = (el, newParent) => {
  newParent.appendChild(el);
};

const l = document.getElementById("old-parent").childNodes.length;
const a = document.getElementById("old-parent");
const b = document.getElementById("new-parent");
for (let i = l; i >= 0; i--) {
  setParent(a.childNodes[i], b);
}

to define the setParent function to new el as a child of newParent.

Then we select the old parent and assign it to a and select the new parent and assign it to b.

Next we use a for loop to loop through a‘s childNodes and move them to b with setParent.

We loop through the childNodes backward so that the order of the child nodes left in a won’t be affected by the loop.

Conclusion

To move all HTML element children to another parent using JavaScript, we can use the appendChild method.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.