Remove an Element

Avatar of Chris Coyier
Chris Coyier on

For whatever reason, an element can’t destroy itself in JavaScript. jQuery has a method for this, which is nice because this is how we think:

$(".remove-me").remove();

But there is no direct equivalent in JavaScript. Instead you’ll need to select the parent element and use removeChild.

So if you have:

<div class="module">
  <p>Stuff.</p>
  <div class="remove-me">...</div>
</div>

You’ll need to do:

var thingToRemove = document.querySelectorAll(".remove-me")[0];

thingToRemove.parentNode.removeChild(thingToRemove);

Or if you had a reference to an element and wanted to empty out all the elements inside it, but keep it:

mydiv = document.getElementById('empty-me');
while (mydiv.firstChild) {
  mydiv.removeChild(mydiv.firstChild);
}