Hide an Element by Class using JavaScript

avatar

Borislav Hadzhiev

Tue Dec 28 20212 min read

Hide an Element by Class Name using JavaScript #

To hide an element by a class:

  1. Select a collection of the elements with the specific class using getElementsByClassName method.
  2. Access an index of the collection to get the element you want to hide.
  3. Set the element's style.visibility property to hidden.

Here is the HTML for the examples in this article.

index.html
<!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.

index.js
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.

index.js
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.

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.

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.

index.js
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.

If you click on the button element from the example, the 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.

Use the search field on my Home Page to filter through my more than 1,000 articles.