HTML5 Zone is brought to you in partnership with:

Catalin Rosu, a.k.a Red, is a professional web designer and developer who loves to be creative and enjoys CSS techniques. You can find articles and tutorials on front-end web development by visiting his blog at red-team-design.com. Also, you can connect with him on Twitter as @catalinred. Catalin is a DZone MVB and is not an employee of DZone and has posted 27 posts at DZone. You can read more from them at their website. View Full User Profile

Removing an element with the plain JavaScript remove() method

04.30.2013
| 8239 views |
  • submit to reddit

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.

JavaScript remove() method

The bulletproof way

Assuming we have the following HTML element:

<div id="myDiv">test</div>

… to remove it from the DOM tree, you would need to run the following JavaScript lines:

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

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:

$('#myDiv').remove();

The new way. FTW.

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

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

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.



Published at DZone with permission of Catalin Red, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)