Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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> 
like image 901
Drew Noakes Avatar asked Jan 03 '14 18:01

Drew Noakes


People also ask

How do you move an element from one element to another?

All you have to do is select the element(s) you want to move, then call an “adding” method such as append() , appendTo() or prepend() to add the selected elements to another parent element. jQuery automatically realises that the element(s) to add already exist in the page, and it moves the element(s) to the new parent.

How do you make an element of another child?

Using the appendChild method getElementById() method then we need to use the appendChild() method to move child element into a parent. The appendChild method inserts the specified element at the end of a parent node list.

What is parent and child relationship in JavaScript?

The nodes in the node tree have a hierarchical relationship to each other. The terms parent, child, and sibling are used to describe the relationships. In a node tree, the top node is called the root (or root node)


1 Answers

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

like image 64
crush Avatar answered Sep 23 '22 12:09

crush