How to Remove DOM Elements with JavaScript

Learn about two different ways to quickly remove or hide elements from the DOM with JavaScript.

There are two ways to remove/hide elements from the DOM with JavaScript. Ask yourself “am I going to need to bring this element back again at some point?”.

If the answer is yes, then you should hide your element with the style property:

const hideElement = document.querySelector('#element-to-hide')
hideElement.style.display = 'none'

If you don’t need to bring the element back again, use this method:

const removeElement = document.querySelector('#element-to-remove')
removeElement.parentNode.removeChild(removeElement)

Remember that when using querySelector() to select elements, # is for elements with ID attributes, . is for classes.