我想将一个DIV元素移动到另一个元素中。例如,我想移动此(包括所有子对象):
<div id="source">
...
</div>
在这方面:
<div id="destination">
...
</div>
所以我有这个:
<div id="destination">
<div id="source">
...
</div>
</div>
我想将一个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);
过来看。
其他回答
使用普通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);
过来看。
您也可以尝试:
$("#destination").html($("#source"))
但这将完全覆盖#destination中的所有内容。
如果要放置元素的div中包含内容,并且希望元素显示在主要内容之后:
$("#destination").append($("#source"));
如果要放置元素的div中包含内容,并且希望在主要内容之前显示元素:
$("#destination").prepend($("#source"));
如果要放置元素的div为空,或者要完全替换它:
$("#element").html('<div id="source">...</div>');
如果要在上述任一项之前复制元素:
$("#destination").append($("#source").clone());
// etc.
Bekim Bacaj回答的肮脏尺寸改进:
div{border:1px实心;margin:5px}<div id=“source”onclick=“destination.appendChild(this)”>单击我</div><div id=“destination”></分区>
我注意到insertAfter&after或insertBefore&before之间存在巨大的内存泄漏和性能差异。。如果您有大量的DOM元素,或者需要在MouseMove事件中使用after()或before(),那么浏览器内存可能会增加,接下来的操作将非常缓慢。
我刚刚经历的解决方案是使用inserBefore代替before(),并使用insertAfter代替after()。