How to Remove an Element by its ID Using Native JavaScript
In standard JavaScript, removing an element from the DOM requires accessing its parent node first:
var element = document.getElementById("element-id"); element.parentNode.removeChild(element);
This approach seems a bit convoluted, prompting the question: why is JavaScript designed this way?
The Solution: Extending DOM Functions
While modifying native DOM functions is not always ideal, the following polyfill works seamlessly in modern browsers:
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]); } } }
With this polyfill, you can remove elements conveniently:
document.getElementById("my-element").remove();
document.getElementsByClassName("my-elements").remove();
Note: This solution does not work in IE 7 and below.
Modern Solution: Node.remove()
In recent browsers, the node.remove() function can be used without the polyfill:
document.getElementById("my-element").remove();
[...document.getElementsByClassName("my-elements")].map(n => n && n.remove());
These functions are supported by all modern browsers, excluding IE. For more details, refer to the MDN documentation.
The above is the detailed content of How to Efficiently Remove DOM Elements by ID in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!