问题描述
我的 html 代码大致如下:
<div id="id2"><p>一些html</p><span>也许更多</span><div id="id3"><p>这里有不同的文字</p><输入类型=文本"><span>甚至可能是一个表单项</span>
我的 html 代码大致如下:
<div id="id2"><p>一些html</p><span>也许更多</span><div id="id3"><p>这里有不同的文字</p><输入类型=文本"><span>甚至可能是一个表单项</span>
很明显,它不止于此,但这是基本思想.我需要做的是切换#id2和#id3的位置,所以结果是:
<div id="id3">...</div><div id="id2">...</div>
有谁知道可以读写两个节点(及其所有子节点)以便交换它们在 DOM 中的位置的函数(我确定我不是第一个需要此功能的人)?
在这种情况下,document.getElementById('id1').appendChild(document.getElementById('id2'));
做把戏.
更一般地,您可以使用 insertBefore()
.
I have html code that looks roughly like this:
<div id="id1">
<div id="id2">
<p>some html</p>
<span>maybe some more</span>
</div>
<div id="id3">
<p>different text here</p>
<input type="text">
<span>maybe even a form item</span>
</div>
</div>
Obviously there's more to it than that, but that's the basic idea. What I need to do is switch the location of #id2 and #id3, so the result is:
<div id="id1">
<div id="id3">...</div>
<div id="id2">...</div>
</div>
Does anyone know of a function (I'm sure I'm not the first person to require this functionality) that can read and write the two nodes (and all their children) so as to swap their location in the DOM?
In this case, document.getElementById('id1').appendChild(document.getElementById('id2'));
should do the trick.
More generally you can use insertBefore()
.
这篇关于“剪切和粘贴"- 使用 Javascript 在 DOM 中移动节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!