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

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

在这方面:

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

所以我有这个:

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

当前回答

尝试纯JavaScript:destination.appendChild(源代码);。

onclick=function(){destination.appendChild(源)};第二部分{边距:.1em;}#目的地{边框:实心1px红色;}#来源{边框:实心1px灰色;}<div id=destination>###</div><div id=源>***</div>

其他回答

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

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

您可以使用:

为了在后面插入,

jQuery("#source").insertAfter("#destination");

为了插入另一元件内部,

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

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

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

如果您想要快速演示并了解有关如何移动元素的更多详细信息,请尝试以下链接:

http://html-tuts.com/move-div-in-another-div-with-jquery


下面是一个简短的示例:

要在元素上方移动:

$('.whatToMove').insertBefore('.whereToMove');

要在元素后移动,请执行以下操作:

$('.whatToMove').insertAfter('.whereToMove');

要在元素内移动,请在该容器内的所有元素上方:

$('.whatToMove').prependTo('.whereToMove');

要在元素内移动,请在该容器内的所有元素之后:

$('.whatToMove').appendTo('.whereToMove');

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

过来看。