Over a million developers have joined DZone.

Removing an element with the plain JavaScript remove() method

· Web Dev Zone

Make the transition to Node.js if you are a Java, PHP, Rails or .NET developer with these resources to help jumpstart your Node.js knowledge plus pick up some development tips.  Brought to you in partnership with IBM.

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");

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.

Learn why developers are gravitating towards Node and its ability to retain and leverage the skills of JavaScript developers and the ability to deliver projects faster than other languages can.  Brought to you in partnership with IBM.


Published at DZone with permission of Catalin Red, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}