46

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.

2

11 Answers 11

54

In the absence of jQuery, I would use 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

2
  • Thanks for the new answer to an old question! Definitely much better with the built in method.
    – MrGlass
    Apr 4, 2016 at 14:22
  • Thankfully with IE officially dead this should now work on just about any browser. For anyone still looking for fixes like this, if you need to include a "document ready" function just insert the code above inside the docReady(function() { // Insert the above code here }); and include the docReady function from here stackoverflow.com/questions/9899372/… Aug 24, 2021 at 10:41
34

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.

21

Late answer, but I found out that this is the simplest solution (if you don't use jQuery):

var myClasses = document.querySelectorAll('.my-class'),
    i = 0,
    l = myClasses.length;

for (i; i < l; i++) {
    myClasses[i].style.display = 'none';
}

Demo

3
  • you have a small bug in the code: at the end of first 2 lines of code you should have ";" not ",". With that fixed the code runs perfect Jul 31, 2014 at 7:03
  • Not a bug, @alexalex. I declare variables separated with commas. See stackoverflow.com/questions/11076750/… for more info
    – HoffZ
    Jul 31, 2014 at 10:55
  • 4
    thanks for pointing that out to me and sorry for the first unwell verified comment, I tried to help nothing else :) - I've ended up learning something new :) Jul 31, 2014 at 11:20
11
function getElementsByClassName(classname, node)  {
    if(!node) node = document.getElementsByTagName("body")[0];
    var a = [];
    var re = new RegExp('\\b' + classname + '\\b');
    var els = node.getElementsByTagName("*");
    for(var i=0,j=els.length; i<j; i++)
        if(re.test(els[i].className))a.push(els[i]);
    return a;
}

var elements = new Array();
elements = getElementsByClassName('yourClassName');
for(i in elements ){
     elements[i].style.display = "none";
}
2
  • 1
    This would be improved by testing for and using the built-in document.getElementsByClassName() method where present.
    – Tim Down
    Jan 10, 2011 at 10:04
  • I'm getting issues in chrome & IE with this. chrome console has an error of "Cannot set property 'display' of undefined"
    – MrGlass
    Jan 11, 2011 at 2:38
10

I would propose a different approach. Instead of changing the properties of all objects manually, let's add a new CSS to the document:

/* License: CC0 */
var newStylesheet = document.createElement('style');
newStylesheet.textContent = '.classname { display: none; }';
document.head.appendChild(newStylesheet);
1
  • 1
    I was looking for this answer to give it an upvote! Nov 17, 2020 at 18:20
4

As simple as the following:

let elements = document.querySelectorAll('.custom-class')

elements.forEach((item: any) => {
  item.style.display = 'none'
})

With that, you avoid all the looping, indexing, and such.

2

In modern JS, this one-liner will do:

document.querySelectorAll('.my-class').forEach(el => el.hidden = true);
0

Using pure HTML\5 Using HTML safe property names \ values. Pure JavaScript conventional access, target and manipulation of the cssRule of interest.

p.s.: No recursion iteration no recursive calls to DOM and no element iteration and value assignments. Makes this the fastest possible solution, where the only bottleneck is the machine dependent rendering and refresh capability.

onclick = function( ) {
    with( document.styleSheets.style1.cssRules[0] )
    style.display = style.display ? "" : "none";
}
.showHide{ 
     color: #777;
}
<!DOCTYPE html>
<html>
<head>
<style id=style1>
.showHide{
}
</style>
</head>
<body>
   <div class=showHide>hide this element</div>
   <div class=showHide>hide this element</div>
   <div class=showHide>hide this element</div>
   <div class=dontHide>this element will not hide</div>
   <div class=showHide>hide this element</div>
</body>
</html>

2
  • This is clever, but I'd rather keep the current answer as I think it is has more general purpose use in 2021. I will probably use this trick elsewhere though :)
    – MrGlass
    Jul 20, 2021 at 2:04
  • 1
    That's where you're wrong @MrGlass. There's no solution more faster, more general, and more 2021++ than the above. Furthermore, there's nothing more Universal and Powerful than conventional code approach and solution of certain tasks. Thanks for reading. It was already morning over here and I accidentally posted an unfinished and unedited response. Jul 23, 2021 at 19:49
0

I really liked @Haritsinh Gohil's answer above, which inspired this answer that will toggle the visibility of the item using the hidden attribute

  function toggle() {
      document.querySelectorAll('div.sad').forEach(function(elem) {
          elem.hidden = !elem.hidden;
      });
  }
<button onclick="toggle()">I'm a button, click me to hide the saddies</button>

<div id="parent">
  <div class="happy">
    :)
  </div>
  <div class="sad">
    :(
  </div>
  <div class="sad">
    :'(
  </div>
  <div class="angry">
    >:(
  </div>
</div>

-1

jQuery solution is straightforward:

$(".className").hide();
1
  • 3
    OP asked for plain javascript. May 19, 2022 at 13:01
-3

Assuming you are dealing with a single class per element:

function swapCssClass(a,b) {
    while (document.querySelector('.' + a)) {
        document.querySelector('.' + a).className = b;
    }
}

and then call simply call it with

swapCssClass('x_visible','x_hidden');
1
  • 1
    Consider using document.getElementsByClassName instead of piecing together the selector
    – shea
    Mar 19, 2016 at 3:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.