且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

按ID删除元素

更新时间:2023-12-03 21:22:46

DOM组织在一个节点树中,每个节点都有一个值,以及一个列表对其子节点的引用。所以 element.parentNode.removeChild(element)完全模仿内部发生的事情:首先你去父节点,然后删除对子节点的引用。

The DOM is organized in a tree of nodes, where each node has a value, along with a list of references to its child nodes. So element.parentNode.removeChild(element) mimics exactly what is happening internally: First you go the the parent node, then remove the reference to the child node.

从DOM4开始,提供了一个辅助函数来执行相同的操作: element.remove() 。此适用于87%的浏览器(截至2016年),但不适用于IE 11.如果您需要支持旧浏览器,可以:

As of DOM4, a helper function is provided to do the same thing: element.remove(). This works in 87% of browsers (as of 2016), but not IE 11. If you need to support older browsers, you can:

  • Remove elements via the parent node, as in the question,
  • modify the native DOM functions, as in Johan Dettmar's answer, or
  • use a DOM4 polyfill.