Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
158 views
in Technique[技术] by (71.8m points)

javascript - 按ID删除元素(Remove element by id)

When removing an element with standard JavaScript, you must go to its parent first:

(使用标准JavaScript删除元素时,必须首先转到其父元素:)

var element = document.getElementById("element-id");
element.parentNode.removeChild(element);

Having to go to the parent node first seems a bit odd to me, is there a reason JavaScript works like this?

(首先必须去父节点对我来说有点奇怪,JavaScript是否有这样的原因?)

  ask by Zaz translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I know that augmenting native DOM functions isn't always the best or most popular solution, but this works fine for modern browsers.

(我知道,增强本机DOM功能并不总是最好的或最受欢迎的解决方案,但是对于现代浏览器来说,这很好。)

Element.prototype.remove = function() {
    this.parentElement.removeChild(this);
}
NodeList.prototype.remove = HTMLCollection.prototype.remove = function() {
    for(var i = this.length - 1; i >= 0; i--) {
        if(this[i] && this[i].parentElement) {
            this[i].parentElement.removeChild(this[i]);
        }
    }
}

And then you can remove elements like this

(然后您可以删除这样的元素)

document.getElementById("my-element").remove();

or

(要么)

document.getElementsByClassName("my-elements").remove();

Note: this solution doesn't work for IE 7 and below.

(注意:此解决方案不适用于IE 7及更低版本。)

For more info about extending the DOM read this article .

(有关扩展DOM的更多信息,请阅读本文 。)

EDIT : Reviewing my answer in 2019, node.remove() has come to the rescue and can be used as follows (without the polyfill above):

(编辑 :回顾我在2019年的答案, node.remove()可以解决问题,并且可以按以下方式使用(没有上面的polyfill):)

document.getElementById("my-element").remove();

or

(要么)

[...document.getElementsByClassName("my-elements")].map(n => n && n.remove());

These functions are available in all modern browsers (not IE).

(这些功能在所有现代浏览器(不是IE)中都可用。)

Read more on MDN .

(阅读有关MDN的更多信息。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...