Borislav Hadzhiev
Tue Dec 28 2021·2 min read
Photo by Patrick Hendry
To hide an element by a class:
getElementsByClassName
method.style.visibility
property to hidden
.Here is the HTML for the examples in this article.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div class="box">Box</div> <button id="btn">Hide Box</button> <script src="index.js"></script> </body> </html>
And here is the related JavaScript code.
const btn = document.getElementById('btn'); btn.addEventListener('click', () => { const box = document.getElementsByClassName('box')[0]; // 👇️ hides element (still takes up space on page) box.style.visibility = 'hidden'; // 👇️ removes element from DOM // box.style.display = 'none'; });
We added an event listener to a button element that hides a div
on click.
We used the
document.getElementsByClassName
method to get an HTMLCollection
of elements, from which we accessed the first
element (index 0).
If you need to hide all of the elements with the specific class name, you can
use a for...of
loop to iterate over the HTMLCollection
.
const btn = document.getElementById('btn'); btn.addEventListener('click', () => { const boxes = document.getElementsByClassName('box'); for (const box of boxes) { // 👇️ hides element box.style.visibility = 'hidden'; // 👇️ removes element from DOM // box.style.display = 'none'; } });
This code snippet hides all of the elements that have a class of box
.
We used the visibility css property in the examples, however you might need the display property depending on your use case.
visibility
property is set to hidden
, it still takes up space on the page, however the element is invisible (not drawn). It still affects the layout on your page as normal.When an element's display
property is set to none
, the element is removed
from the DOM and has no effect on the layout. The document is rendered as though
the element does not exist.
Here is an example that uses the display
property to hide an element by its
class name.
const btn = document.getElementById('btn'); btn.addEventListener('click', () => { const box = document.getElementsByClassName('box')[0]; // 👇️ removes element from DOM box.style.display = 'none'; });
The difference is that when the element's display property is set to none
, it
no longer takes space on the page.
div
element is removed from the DOM and the button element takes its place.If however, you set the element's visibility
property to hidden
, the div
element still takes up space on the page, but is invisible.