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

Drew Noakes picture Drew Noakes · Jan 3, 2014 · Viewed 109.5k times · Source

Imagine:

<div id="old-parent">
    <span>Foo</span>
    <b>Bar</b>
    Hello World
</div>
<div id="new-parent"></div>

What JavaScript can be written to move all the child nodes (both elements, and text nodes) from old-parent to new-parent without jQuery?

I don't care about whitespace between nodes, though I expect to catch the stray Hello World, they would need to be migrated as-is too.

EDIT

To be clear, I want to end up with:

<div id="old-parent"></div>
<div id="new-parent">
    <span>Foo</span>
    <b>Bar</b>
    Hello World
</div>

The answer of the question from which this is a proposed duplicate would result in:

<div id="new-parent">
    <div id="old-parent">
        <span>Foo</span>
        <b>Bar</b>
        Hello World
    </div>
</div>

Answer

crush picture crush · Jan 3, 2014

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]);
}