如何在JavaScript中交换DOM子节点? [英] How to swap DOM child nodes in JavaScript?

查看:90
本文介绍了如何在JavaScript中交换DOM子节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是最简单的交换子节点顺序的方法?

What is the easiest way to swap the order of child nodes?

例如我希望childNode [3]成为childNode [4],反之亦然。

For example I want childNode[3] to be childNode[4] and vice-versa.

推荐答案

不需要克隆。您可以通过以下方式将一个节点移动到另一个节点:

There is no need for cloning. You can just move one node before the other with this:

childNode[4].parentNode.insertBefore(childNode[4], childNode[3]);

你得到节点的父节点。然后,您可以在父项上调用insertBefore方法,并将其传递给childNode [4]节点,并在childNode [3]之前告诉它要插入它。这将给你交换订单的结果,所以4将在3之前完成。

You get the parent of the node. You then call the insertBefore method on the parent and you pass it the childNode[4] node and tell it you want it inserted before childNode[3]. That will give you the result of swapping their order so 4 will be before 3 when it's done.

参考 insertBefore之前的文档

插入到DOM中的任何节点已经在DOM中的DOM首先被自动删除,然后插入,所以不需要手动删除它。

Any node that is inserted into the DOM that is already in the DOM is first removed automatically and then inserted back so there is no need to manually remove it first.

这篇关于如何在JavaScript中交换DOM子节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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