如何使用 JavaScript 将所有 HTML 元素的子元素移动到另一个父元素?

想象一下:

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

在没有 jQuery 的情况下,可以编写哪些 JavaScript 来将所有子节点(包括元素和文本节点)从 old-parent移动到 new-parent

我不关心节点之间的空格,虽然我希望捕获杂散的 Hello World,但是它们也需要按原样迁移。

剪辑

先说清楚,我想说的是:

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

对这一拟议重复的问题的答复将是:

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

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

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!

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

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

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

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.