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

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


DEMO

Basically, you want to loop through each direct descendent of the old-parent node, and move it to the new parent. Any children of a direct descendent will get moved with it.

var newParent = document.getElementById('new-parent');
var oldParent = document.getElementById('old-parent');

while (oldParent.childNodes.length > 0) {
    newParent.appendChild(oldParent.childNodes[0]);
}

~ Answered on 2014-01-03 18:18:52


Most Viewed Questions: