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

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>

This question is related to javascript html dom-manipulation

The answer is


Here's a simple function:

function setParent(el, newParent)
{
    newParent.appendChild(el);
}

el's childNodes are the elements to be moved, newParent is the element el will be moved to, so you would execute the function like:

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

Here is the Demo


If you not use - in id's names then you can do this

_x000D_
_x000D_
oldParent.id='xxx';_x000D_
newParent.id='oldParent';_x000D_
xxx.id='newParent';_x000D_
oldParent.parentNode.insertBefore(oldParent,newParent);
_x000D_
#newParent { color: red }
_x000D_
<div id="oldParent">_x000D_
    <span>Foo</span>_x000D_
    <b>Bar</b>_x000D_
    Hello World_x000D_
</div>_x000D_
<div id="newParent"></div>
_x000D_
_x000D_
_x000D_


This answer only really works if you don't need to do anything other than transferring the inner code (innerHTML) from one to the other:

// Define old parent
var oldParent = document.getElementById('old-parent');

// Define new parent
var newParent = document.getElementById('new-parent');

// Basically takes the inner code of the old, and places it into the new one
newParent.innerHTML = oldParent.innerHTML;

// Delete / Clear the innerHTML / code of the old Parent
oldParent.innerHTML = '';

Hope this helps!


Modern way:

newParent.append(...oldParent.childNodes);
  1. .append is the replacement for .appendChild. The main difference is that it accepts multiple nodes at once and even plain strings, like .append('hello!')
  2. oldParent.childNodes is iterable so it can be spread with ... to become multiple parameters of .append()

Compatibility tables of both (in short: Edge 17+, Safari 10+):