To move all HTML element children to another parent using JavaScript, we use the appendChild
method.
For instance, we write
const newParent = document.getElementById("new-parent");
const oldParent = document.getElementById("old-parent");
const move = () => {
while (oldParent.childNodes.length > 0) {
newParent.appendChild(oldParent.childNodes[0]);
}
};
to select the new and old parent element with getElementById
.
Then we define the move
function to move the elements in the old parent to the new one.
In it, we use a while loop to check if there’re any child nodes left in the old parent with oldParent.childNodes.length > 0
.
If there’re any left, then we call appendChild
with oldParent.childNodes[0]
to move the first child node in the old parent to the new parent.