Home > Web Front-end > JS Tutorial > How to Efficiently Remove DOM Elements by ID in JavaScript?

How to Efficiently Remove DOM Elements by ID in JavaScript?

Barbara Streisand
Release: 2024-12-18 17:31:11
Original
583 people have browsed it

How to Efficiently Remove DOM Elements by ID in JavaScript?

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);
Copy after login

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]);
        }
    }
}
Copy after login

With this polyfill, you can remove elements conveniently:

document.getElementById("my-element").remove();
Copy after login
Copy after login
document.getElementsByClassName("my-elements").remove();
Copy after login

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();
Copy after login
Copy after login
[...document.getElementsByClassName("my-elements")].map(n => n && n.remove());
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template