Hide the all elements by class using JavaScript
In this tutorial, we are going to learn about how to hide the all elements by class using JavaScript.
Consider, we have a following html elements.
<div class="container">
<div class="box">box 1</div>
<div class="box">box 2</div>
<div class="box">box 3</div>
</div>Now, we need to hide the above elements by using the classname box.
Hiding all elements by class
To hide all elements by class in JavaScript:
-
First, we need to access the elements inside the JavaScript using the
document.getElementsbyClassName()method. -
Iterate over the each class using for..of loop.
-
Then set its
style.displayproperty tonone.
Here is an example:
<div class="container">
<div class="box">box 1</div>
<div class="box">box 2</div>
<div class="box">box 3</div>
</div>const elements = document.getElementsbyClassName("box");
for (const el of elements){
el.style.display= "none";
}Using style.visibility property
Similarly, we can also hide all elements by a specific class by using the element’s style.visibility property.
Here is an example:
const element = document.getElementsbyClassName("box");
for (const el of elements){
element.style.visibility= "hidden";
}In the example above:
First, we have accessed the html element using the document.getElementsbyClassName() method then on each iteration we are updating the element’s style.visibility property to hidden. so it hides the element from a dom.
The main difference between style.display and style.visibility properties are:
-
When we set a
style.displayproperty tonone, it removes the element completely from the dom . -
When we set a
style.displayproperty tohidden, it just hides the element but doesn’t remove it in the dom.


