Treehouse: Grow your CSS skills. Land your dream job.

Last updated on:

Remove an Element

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

Comments

  1. Andy Hoffman
    Permalink to comment#

    How about using a facade pattern for this task?

    function myWrapper(element) {
      this.element = element;
    }
    
    myWrapper.prototype.remove = function() {
      this.element.parentNode.removeChild(this.element);
    }
    
    var some_el = new myWrapper(
      document.getElementById("some_el)
    );
    
    some_el.remove();
    
  2. ffffdessscn
    Permalink to comment#

    Nice but to difficult for most html, css and jquery people.

    • Nah you’ll be OK.

      Think of it like this:

      // jQuery: thingToRemove = $(".remove-me");
      var thingToRemove = document.querySelectorAll(".remove-me")[0];
      
      // jQuery: thingToRemove.remove();
      thingToRemove.parentNode.removeChild(thingToRemove);
      

Leave a Comment

Posting Code

We highly encourage you to post problematic HTML/CSS/JavaScript over on CodePen and include the link in your post. It's much easier to see, understand, and help with when you do that.

Markdown is supported, so you can write inline code like `<div>this</div>` or multiline blocks of code in in triple backtick fences like this:

```
<script>
  function example() {
    element.innerHTML = "<div>code</div>";
  }
</script>
```