按ID删除元素 [英] Remove element by id

查看:290
本文介绍了按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?

推荐答案

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.

这篇关于按ID删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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