Borislav Hadzhiev
Last updated: Dec 29, 2021
Check out my new book
To hide all elements by class:
getElementsByClassName
method to get a collection of HTML elements.for...of
loop.style.display
property to none
on each element.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 1</div> <div class="box">Box 2</div> <div class="box">Box 3</div> <button id="btn">Click me</button> <script src="index.js"></script> </body> </html>
And here is the related JavaScript code.
const btn = document.getElementById('btn'); btn.addEventListener('click', () => { const boxes = document.getElementsByClassName('box'); for (const box of boxes) { // 👇️ Remove element from DOM box.style.display = 'none'; // 👇️ hide element (still takes up space on page) // box.style.visibility = 'hidden'; } });
We used the
document.getElementsByClassName()
method to get an HTMLCollection
of the elements with the specific class.
We used the
for...of
loop to iterate over the collection and on each iteration, we set the element's
display property to
none
to hide it.
Note that the getElementsByClassName
method returns an HTML collection and not
an array. If you want to convert the collection to an array, pass it to the
Array.from
method.
const btn = document.getElementById('btn'); btn.addEventListener('click', () => { // 👇️ Use Array.from to convert to array const boxes = Array.from(document.getElementsByClassName('box')); boxes.forEach(box => { // 👇️ Remove element from DOM box.style.display = 'none'; // 👇️ hide element (still takes up space on page) // box.style.visibility = 'hidden'; }); });
After converting the HTMLCollection
to an array, we are able to use any of the
array-supported methods in JavaScript, e.g. Array.forEach
.
To hide each element, we set its display
property to none
, however you might
need to use the
visibility
property depending on your use case.
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.On the other hand, when an element's 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.
Here is an example that uses the visibility
property to hide all of the
elements by class.
const btn = document.getElementById('btn'); btn.addEventListener('click', () => { const boxes = Array.from(document.getElementsByClassName('box')); boxes.forEach(box => { // 👇️ hide element (still takes up space on page) box.style.visibility = 'hidden'; }); });
If you click on the button, you'll see that the div
elements disappear,
however they still take up space on the page.
This is the difference between setting visibility
to hidden
and display
to
none
.