“切割和粘贴” - 使用Javascript在DOM中移动节点 [英] "Cut and Paste" - moving nodes in the DOM with Javascript

查看:112
本文介绍了“切割和粘贴” - 使用Javascript在DOM中移动节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的HTML代码大致如下:

 < div id =id1> 
< div id =id2>
< p>某些html< / p>
< span>可能还有一些< / span>
< / div>
< div id =id3>
< p>不同的文本< / p>
< input type =text>
< span>甚至可能是一个表单项< / span>
< / div>
< / div>

显然,这比它更多,但这是基本的想法。我需要做的是切换#id2和#id3的位置,结果是:

 < div id = ID1 > 
< div id =id3> ...< / div>
< div id =id2> ...< / div>
< / 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中移动节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆