remove element by id

How to Remove Element By Id in JS

Often web developers need to remove element by id or class attributes in JavaScript. While it is easy to do this using third party JS libraries like jQuery, it used to be a little tricky to do it using plain JavaScript. In this article, we will learn how to remove element by ID in JS.


How to Remove Element By Id in JS

Let us say you have the following HTML element.

<a id="myLink">My Link</a>

Generally, most tutorials require you to select the element first, then its parent, and then remove the element, as shown below.

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

But most modern browsers like Chrome, Firefox and Edge offer a new way to do this.

document.getElementById("myLink").remove();
or

[...document.getElementsByClassName("myLink")].map(n => n && n.remove());

In this case, we use getElementByID() function to select the element, and then call remove() function to remove it.

Another simple way is to make its outerHTML as blank.

document.getElementById("myLink").outerHTML = "";

If you are using an older browser version, you may need to create a prototype function remove() to define how the element is to be deleted.

Element.prototype.remove = function() {
    this.parentElement.removeChild(this);
}

Once you have defined this prototype function, you can call it as shown below.

document.getElementById("myLink").remove();

In this article, we have learnt how to remove element by ID in JavaScript.

Also read:

How to Write to File in NodeJS
How to Export JS Array to CSV File
How to Convert Unix Timestamp to Datetime in Python
How to Smooth Scroll on Clicking Links
How to Import SQL File in MySQL Using Command Line

Leave a Reply

Your email address will not be published.