Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide all elements with class using plain Javascript

Tags:

javascript

I normally use document.getElementById('id').style.display = 'none' to hide a single div via Javascript. Is there a similarly simple way to hide all elements belonging to the same class?

I need a plain Javascript solution that does not use jQuery.

Apparently SO wants me to edit this to clarify that it is not a question about modifying strings. It's not.

like image 578
MrGlass Avatar asked Jan 10 '11 07:01

MrGlass


People also ask

How do you hide items in JavaScript?

Style display property is used to hide and show the content of HTML DOM by accessing the DOM element using JavaScript/jQuery. To hide an element, set the style display property to “none”.

Can we hide HTML elements using JavaScript?

Using Css style we can hide or show HTML elements in javascript. Css provides properties such as block and none to hide/show the HTML elements.


2 Answers

In the absence of jQuery, I would use something like this:

<script>     var divsToHide = document.getElementsByClassName("classname"); //divsToHide is an array     for(var i = 0; i < divsToHide.length; i++){         divsToHide[i].style.visibility = "hidden"; // or         divsToHide[i].style.display = "none"; // depending on what you're doing     } <script> 

This is taken from this SO question: Hide div by class id, however seeing that you're asking for "old-school" JS solution, I believe that getElementsByClassName is only supported by modern browsers

like image 125
Dairy Window Avatar answered Oct 02 '22 08:10

Dairy Window


There are many ways to hide all elements which has certain class in javascript one way is to using for loop but here i want to show you other ways to doing it.

1.forEach and querySelectorAll('.classname')

document.querySelectorAll('.classname').forEach(function(el) {    el.style.display = 'none'; }); 

2.for...of with getElementsByClassName

for (let element of document.getElementsByClassName("classname")){    element.style.display="none"; } 

3.Array.protoype.forEach getElementsByClassName

Array.prototype.forEach.call(document.getElementsByClassName("classname"), function(el) {     el.style.display = 'none'; }); 

4.[ ].forEach and getElementsByClassName

[].forEach.call(document.getElementsByClassName("classname"), function (el) {     el.style.display = 'none'; }); 

i have shown some of the possible ways, there are also more ways to do it, but from above list you can Pick whichever suits and easy for you.

Note: all above methods are supported in modern browsers but may be some of them will not work in old age browsers like internet explorer.

like image 44
Haritsinh Gohil Avatar answered Oct 02 '22 07:10

Haritsinh Gohil