In an earlier article, we looked at how to create and add a new element into the DOM using JavaScript. Today, let us look at how to remove elements from the DOM with JavaScript.

There are two ways to remove an element from the DOM in JavaScript. You can either hide the DOM element using inline styles or entirely 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 helpful if you temporarily want to hide the element from the DOM and bring it back at some point based on 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.

Remove an element using 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 removing an element is 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 an 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.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.