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

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


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()

It's supported by every browser except IE.