How to remove a DOM Element with JavaScript

by||1 min read

In times of Single Page Applications (SPA) and modern frameworks this task is handled for you by the framework. For instance React removes elements from the DOM if a component is not rendered. But how to remove element from DOM in plain JavaScript?

For many cases we can use style="display: none". But this is only useful when you would like to hide elements. They will still be present in the DOM (but not rendered by the Browser).

To permanently remove an element from the DOM, we can use the built in removeChild function on an element in JavaScript.

An example says more than 1000 words:

Let's take a sample code like this:

<html>
  <body>
    <div id="myTarget">This needs to go</div>
  </body>
</html>

We would like to get rid of the DIV element with the Id #myTarget. In JavaScript we can search for this element and apply the removeChild function to it's parent:

// Select our elmement of interest
const targetToRemove = document.querySelector('#myTarget');

// Only perform the remove action on existing elements
if (targetToRemove) {
  targetToRemove.parentElement.removeChild(targetToRemove);
}

By using parentElement.removeChild() you will permanently remove an element from the DOM. Nice! As well, the code above can be safely called multiple times.

Optional Solution

If you don't need to support IE as a browser you can use the remove function on the element itself, like this:

// Select our elmement of interest
const targetToRemove = document.querySelector('#myTarget');

// Only perform the remove action on existing elements
if (targetToRemove) {
  targetToRemove.remove();
}

This way the element removes itself from the document without any involvement of a parent round-trip.

Thank you for reading this far! Let’s connect. You can @ me on Twitter (@debilofant) with comments, or feel free to follow. Please like/share this article so that it reaches others as well.

© Copyright 2022 - Ersocon - All rights reservedVer. 2.3.5.2