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

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

在这方面:

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

所以我有这个:

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

当前回答

我注意到insertAfter&after或insertBefore&before之间存在巨大的内存泄漏和性能差异。。如果您有大量的DOM元素,或者需要在MouseMove事件中使用after()或before(),那么浏览器内存可能会增加,接下来的操作将非常缓慢。

我刚刚经历的解决方案是使用inserBefore代替before(),并使用insertAfter代替after()。

其他回答

我刚刚使用了:

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

我从这里抓起的。

appendChild正是这样做的——基本上是剪切粘贴。

它将移动选定的元素及其所有子节点。

为了完整起见,本文中提到了另一种方法wrap()或wrapAll()。因此,OP的问题可以通过以下方式解决(即,假设<div id=“destination”/>还不存在,以下方法将从头创建这样的包装器-OP不清楚包装器是否已经存在):

$("#source").wrap('<div id="destination" />')
// or
$(".source").wrapAll('<div id="destination" />')

听起来很有希望。然而,当我试图对多个嵌套结构执行$(“[id^=row]”).wrapAll(“<fieldset></fieldset>”)时,如下所示:

<div id="row1">
    <label>Name</label>
    <input ...>
</div>

它正确地包装了那些<div></div>和<input></input>但是有人把<label></标签>。所以我最终使用了显式的$(“row1”).append(“#a_predefined_fieldset”)。所以,YMMV。

使用普通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);

过来看。

我注意到insertAfter&after或insertBefore&before之间存在巨大的内存泄漏和性能差异。。如果您有大量的DOM元素,或者需要在MouseMove事件中使用after()或before(),那么浏览器内存可能会增加,接下来的操作将非常缓慢。

我刚刚经历的解决方案是使用inserBefore代替before(),并使用insertAfter代替after()。