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的更多信息。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…