Friday, May 10, 2013

Removing an element with the plain JavaScript remove() method

JavaScript remove() method
As you might know, the DOM does not supports removing an element directly. When removing an element with JavaScript, you must go to its parent first instead. This was always odd and not so straightforward.

According to DOM level 4 specs, which is the current version in development, there are some new handy mutation methods available: append(), prepend(), before(), after(), replace() and remove(). In this article we’ll focus a bit on one of the new kids on the block, the plain vanilla JavaScript remove() method.

The bulletproof way

Assuming we have the following HTML element:

<div id="myDiv">test</div> remove it from the DOM tree, you would need to run the following JavaScript lines:

var elem = document.getElementById("myDiv");

The jQuery way

If you're using a JavaScript framework like jQuery, to take an element out of the DOM, you have to use the remove() method:


The new way. FTW.

Having already defined the variable elem, here’s how to properly remove that node:

var elem = document.getElementById("myDiv");

Notice the jQuery similarity? This new way is simpler and much more intuitive... for the win.

Browser support

At this time, the support is: Chrome, Opera, Safari and soon Firefox 23. Maybe it's not so awesome for production purposes, but still great for testing and debugging.

However, if you're looking for a larger browser support, there are some polyfills that definitely worth an eye on:

P.S. Beside these new methods, don't forget about the querySelector() as well. That's another cool JavaScript method which is very useful to select an element by class name for example. All these combined, provide a very good support for daily debugging and personal projects without using any framework. Especially if you’re not interested in supporting older browsers like IE7 and lower.