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

127,207

Solution 1

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');

function move() {
  while (oldParent.childNodes.length > 0) {
    newParent.appendChild(oldParent.childNodes[0]);
  }
}
#old-parent {
  background-color: red;
}

#new-parent {
  background-color: green;
}
<div id="old-parent">
  <span>Foo</span>
  <b>Bar</b> Hello World
</div>
<div id="new-parent"></div>
<br>
<button onclick="move()" id="button">Move childs</button>

External link

Solution 2

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+):

Solution 3

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

Share:
127,207
Drew Noakes
Author by

Drew Noakes

Developer on .NET at Microsoft.

Updated on July 15, 2022

Comments

  • Drew Noakes
    Drew Noakes almost 2 years

    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>