// 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
// grab element you want to hide const elem = document.querySelector('#hint') // remove element elem.parentNode.removeChild(elem)
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
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.