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.
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) {
.parentElement.removeChild(targetToRemove);
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.
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) {
.remove();
targetToRemove }
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.