How to remove an element from the DOM in JavaScript

published: 16 Sep 2022

2 min read

How to remove an element from the DOM in JavaScript

Last week, we looked at how to create a new element and insert it to the DOM by using vanilla JavaScript. Today, let us look at how to remove elements from the DOM with JavaScript.

There are two ways to erase an element from the DOM in JavaScript. You can either hide the element by using inline styles or completely remove it.

To hide the element from the DOM in JavaScript, you can use the DOM style property:

// grab element you want to hide
const elem = document.querySelector('#hint');

// hide element with CSS
elem.style.display = 'none';

As you can see above, we just changed the element's display type to none with the help of the style property. This approach is very useful if you temporarily want to hide the element from the DOM, and want to bring it back at some point based on the user interactions.

Alternatively, if you want to remove the element from the DOM entirely, you can use the removeChild() property:

// grab element you want to hide
const elem = document.querySelector('#hint');

// remove element
elem.parentNode.removeChild(elem);

The removeChild() method deletes the given child node of the specified element. It returns the removed node as a Node object, or null if the node does not exist. It works in all modern and old browsers including Internet Explorer.

ES6 remove() Method

The removeChild() method works great to remove an element, but you can only call it on the parentNode of the element you want to remove.

The modern approach to remove an element is to use the remove() method. Just call this method on the element you want to remove from the DOM, like below:

// grab element you want to hide
const elem = document.querySelector('#hint');

// remove element from DOM (ES6 way)
elem.remove();

This method was introduced in ES6 and, at the moment, only works in modern browsers. However, you can use a polyfill to make it compatible with Internet Explorer 9 and higher.

How to remove an element from the DOM in JavaScript | Coding Tips And Tricks

Are we missing something?  Help us improve this article. Reach out to us.

Are you looking for other code tips?

Check out what's on in the category: javascript, programming
Check out what's on in the tag: javascript, programming