我想将一个DIV元素移动到另一个元素中。例如,我想移动此(包括所有子对象):

<div id="source">
  ...
</div>

在这方面:

<div id="destination">
  ...
</div>

所以我有这个:

<div id="destination">
  <div id="source">
    ...
  </div>
</div>

当前回答

使用普通JavaScript解决方案:

// Declare a fragment:
var fragment = document.createDocumentFragment();

// Append desired element to the fragment:
fragment.appendChild(document.getElementById('source'));

// Append fragment to desired element:
document.getElementById('destination').appendChild(fragment);

过来看。

其他回答

您可能需要使用appendTo函数(它将添加到元素的末尾):

$("#source").appendTo("#destination");

或者,您可以使用prependTo函数(添加到元素的开头):

$("#source").prependTo("#destination");

例子:

$(“#appendTo”).click(function(){$(“#moveMeIntoMain”).appendTo($(“#main”));});$(“#prependTo”).click(function(){$(“#moveMeIntoMain”).prependTo($(“#main”));});#主要的,主要的{边框:2px纯蓝色;最小高度:100px;}.moveMeIntoMain{边框:1px纯红色;}<script src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js“></script><div id=“main”>main</div><div id=“moveMeIntoMain”class=“moveMeIntoMain”>将我移动到main</div><button id=“appendTo”>appendTo main</button><button id=“prependTo”>prependTo main</button>

我刚刚使用了:

$('#source').prependTo('#destination');

我从这里抓起的。

使用普通JavaScript解决方案:

// Declare a fragment:
var fragment = document.createDocumentFragment();

// Append desired element to the fragment:
fragment.appendChild(document.getElementById('source'));

// Append fragment to desired element:
document.getElementById('destination').appendChild(fragment);

过来看。

Bekim Bacaj回答的肮脏尺寸改进:

div{border:1px实心;margin:5px}<div id=“source”onclick=“destination.appendChild(this)”>单击我</div><div id=“destination”></分区>

我的解决方案:

移动:

jQuery("#NodesToMove").detach().appendTo('#DestinationContainerNode')

副本:

jQuery("#NodesToMove").appendTo('#DestinationContainerNode')

注意.detach()的用法。复制时,请注意不要复制ID。