我想将一个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>
当前回答
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()。
为了完整起见,本文中提到了另一种方法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。
您可以使用:
为了在后面插入,
jQuery("#source").insertAfter("#destination");
为了插入另一元件内部,
jQuery("#source").appendTo("#destination");
您可以使用纯JavaScript,使用appendChild()方法。。。
appendChild()方法将节点附加为节点的最后一个子节点。提示:如果你想用文本创建一个新段落,请记住将文本创建为附加到段落的文本节点,然后将段落附加到文档中。也可以使用此方法将元素从一个元素移动到另一个提示:使用insertBefore()方法在指定的、现有的、子节点。
所以你可以这样做来完成这项工作,这是我为你创建的,使用appendChild(),运行并查看它如何适用于你的案例:
函数appendIt(){var source=document.getElementById(“源”);document.getElementById(“目标”).appendChild(源);}#来源{颜色:白色;背景:绿色;填充:4px 8px;}#目的地{颜色:白色;背景:红色;填充:4px 8px;}按钮{页边空白:20px;}<div id=“source”><p>来源</p></div><div id=“destination”><p>目的地</p></div><button onclick=“appendIt()”>移动元素</button>
我的解决方案:
移动:
jQuery("#NodesToMove").detach().appendTo('#DestinationContainerNode')
副本:
jQuery("#NodesToMove").appendTo('#DestinationContainerNode')
注意.detach()的用法。复制时,请注意不要复制ID。