Removing any DOM element using JavaScript

There are some things in JavaScript that will to learners seem like an obvious hole. One of these is removing a DOM element. jQuery has a .remove() function, but it’s worth knowing how to do the same thing in raw JavaScript. Besides, it’s deceptively easy:


Object.prototype.remove() = function() {
    this.parentNode.removeChild(this);
}

Because we have added the function to the prototype, we can now call .remove() on any element.

Published by

Adam Hopkinson

A web development manager with interests in UX, design and code.

Leave a Reply

Your email address will not be published. Required fields are marked *