如何使用JavaScript删除HTML中的子节点? [英] How can I remove a child node in HTML using JavaScript?

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

问题描述

有没有像 document.getElementById(FirstDiv)这样的函数。clear()

推荐答案

为了回答原来的问题 - 有很多种方法可以做到这一点,但以下是最简单的。

To answer the original question - there are various ways to do this, but the following would be the simplest.

如果你已经有要删除的子节点的句柄,即您有一个JavaScript变量,用于保存对其的引用:

If you already have a handle to the child node that you want to remove, i.e. you have a JavaScript variable that holds a reference to it:

myChildNode.parentNode.removeChild(myChildNode);

显然,如果您没有使用已经执行此操作的众多库之一,创建一个函数来抽象出来:

Obviously, if you are not using one of the numerous libraries that already do this, you would want to create a function to abstract this out:

function removeElement(node) {
    node.parentNode.removeChild(node);
}






编辑:其他人提到的:如果你有任何事件处理程序连接到要删除的节点,那么您将需要确保在最后一次引用被删除的节点之前断开连接,以免JavaScript解释器漏洞执行不力记忆。


As has been mentioned by others: if you have any event handlers wired up to the node you are removing, you will want to make sure you disconnect those before the last reference to the node being removed goes out of scope, lest poor implementations of the JavaScript interpreter leak memory.

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

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