How to hide a DOM element using plain JavaScript
By Flavio Copes
Learn how to hide a DOM element with plain JavaScript by setting its style.display property to none, then show it again with block or inline.
To hide a DOM element with plain JavaScript, set its style.display property to 'none'.
Every element exposes a style property which you can use to alter the CSS styling properties.
Setting display to 'none' works like writing display: none; in CSS: the element disappears and the page reflows as if it was never there.
Say we have a banner in the page:
<div class="newsletter-banner">Subscribe to my newsletter!</div>
We select it and hide it:
const banner = document.querySelector('.newsletter-banner')
banner.style.display = 'none'
To display it again, set it back to block or inline:
banner.style.display = 'block'
Restoring the original display value
Here’s a pitfall I ran into. Setting display = 'block' to show the element again assumes the element was a block. If your CSS styled it with display: flex or display: grid, forcing block breaks its layout.
The fix is to set the property to an empty string:
banner.style.display = ''
This removes the inline style, and the element goes back to whatever your stylesheet says. I find this safer than remembering the right value for each element.
What if I want the element to keep its space?
display: none removes the element from the layout, so everything below it moves up. Sometimes you want the element invisible but still occupying its spot, so the page doesn’t jump.
For that, use visibility instead:
banner.style.visibility = 'hidden'
Set it back to 'visible' to show it again. The element stays in the flow the whole time, it’s just not painted.
Toggling with a single line
If you need to show and hide the same element repeatedly, checking the current value works fine:
banner.style.display = banner.style.display === 'none' ? '' : 'none'
Notice we toggle between 'none' and the empty string, for the reason we saw above.
One last detail: inline styles set this way have high specificity, they override the rules in your stylesheet. That’s exactly why this technique works, but also why the element won’t respond to CSS display rules again until you clear the inline value.
Related posts about js: