Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove element by id

Tags:

javascript

dom

When removing an element with standard JavaScript, you must go to its parent first:

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

Having to go to the parent node first seems a bit odd to me, is there a reason JavaScript works like this?

like image 293
Zaz Avatar asked Aug 01 '10 18:08

Zaz


People also ask

How do I grab an element by ID?

getElementById() The Document method getElementById() returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.

How do you delete an element?

The remove() method removes an element (or node) from the document.


1 Answers

I know that augmenting native DOM functions isn't always the best or most popular solution, but this works fine for 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]);         }     } } 

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. For more info about extending the DOM read this article.

EDIT: Reviewing my answer in 2019, node.remove() has come to the rescue and can be used as follows (without the polyfill above):

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). Read more on MDN.

like image 139
Johan Dettmar Avatar answered Sep 18 '22 09:09

Johan Dettmar