Removing Elements with Ease: Exploring nativeDOM and node.remove()
When tasked with removing HTML elements in JavaScript, there has long been a perceived oddity: having to first select the parent node. Until recently, the standard way required the following code:
var element = document.getElementById("element-id"); element.parentNode.removeChild(element);
An Improved Approach
For modern browsers, augmenting the native DOM functions offers a solution that feels more intuitive:
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]); } } }
Now, removing elements becomes a breeze:
document.getElementById("my-element").remove();
or
document.getElementsByClassName("my-elements").remove();
The Triumph of node.remove()
In a recent update, node.remove() has emerged as the savior for this task, available in all modern browsers except IE:
document.getElementById("my-element").remove();
or
[...document.getElementsByClassName("my-elements")].map(n => n && n.remove());
While these solutions may not work in IE 7 and below, they provide a much smoother and more logical way of removing elements from the DOM, leaving behind a more efficient and straightforward coding experience.
The above is the detailed content of How Can I Efficiently Remove HTML Elements in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!