通过 id 删除元素 [英] Remove element by id
问题描述
使用标准 JavaScript 删除元素时,必须先转到其父元素:
When removing an element with standard JavaScript, you must go to its parent first:
var element = document.getElementById("element-id");
element.parentNode.removeChild(element);
必须先转到父节点对我来说似乎有点奇怪,JavaScript 有这样工作的原因吗?
Having to go to the parent node first seems a bit odd to me, is there a reason JavaScript works like this?
推荐答案
element.remove()
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 parent node, then remove the reference to the child node.
从 DOM4 开始,提供了一个辅助函数来做同样的事情:element.remove()
.此适用于 96% 的浏览器(截至 2020 年),但不适用于 IE 11.如果您需要支持旧版浏览器,您可以:
As of DOM4, a helper function is provided to do the same thing: element.remove()
. This works in 96% of browsers (as of 2020), but not IE 11. If you need to support older browsers, you can:
- 通过父节点移除元素,如问题,
- 修改原生 DOM 函数,如Johan Dettmar 的回答,或
- 使用 DOM4 polyfill.
这篇关于通过 id 删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!