// 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
// 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.
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.
👋 If you enjoy reading my articles and want to support me to continue creating free tutorials, ☕ Buy me a coffee (cost $5).