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.

MrGlass
  • 9,094
  • 17
  • 64
  • 89
  • Does this answer your question? [How to replace all occurrences of a string in JavaScript](https://stackoverflow.com/questions/1144783/how-to-replace-all-occurrences-of-a-string-in-javascript) – TheWebs Jul 15 '21 at 15:37
  • 2
    @TheWebs I asked this question a decade ago, but I just checked for you and no. This question has literally nothing to do with string manipulation. – MrGlass Jul 19 '21 at 00:36

11 Answers11

52

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

Lukas
  • 610
  • 7
  • 16
Dairy Window
  • 1,307
  • 1
  • 13
  • 9
  • Thanks for the new answer to an old question! Definitely much better with the built in method. – MrGlass Apr 04 '16 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 https://stackoverflow.com/questions/9899372/pure-javascript-equivalent-of-jquerys-ready-how-to-call-a-function-when-t – brianlmerritt Aug 24 '21 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.

Haritsinh Gohil
  • 5,818
  • 48
  • 50
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

HoffZ
  • 7,709
  • 6
  • 36
  • 40
  • 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 – jnhghy - Alexandru Jantea Jul 31 '14 at 07:03
  • Not a bug, @alexalex. I declare variables separated with commas. See http://stackoverflow.com/questions/11076750/what-does-variable-declaration-with-multiple-comma-separated-values-mean-e-g-v for more info – HoffZ Jul 31 '14 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 :) – jnhghy - Alexandru Jantea Jul 31 '14 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";
}
Zhasulan Berdibekov
  • 1,077
  • 3
  • 19
  • 39
  • 1
    This would be improved by testing for and using the built-in `document.getElementsByClassName()` method where present. – Tim Down Jan 10 '11 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 '11 at 02: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);
Mat2
  • 151
  • 2
  • 4
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.

Arthur Serafim
  • 393
  • 2
  • 7
2

In modern JS, this one-liner will do:

document.querySelectorAll('.my-class').forEach(el => el.hidden = true);
connexo
  • 53,704
  • 14
  • 91
  • 128
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>
Bekim Bacaj
  • 5,707
  • 2
  • 24
  • 26
  • 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 '21 at 02: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. – Bekim Bacaj Jul 23 '21 at 19:49
0

jQuery solution is straightforward:

$(".className").hide();
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>
datu-puti
  • 1,306
  • 14
  • 33
-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');
whadar
  • 4,181
  • 4
  • 19
  • 21
  • 1
    Consider using `document.getElementsByClassName` instead of piecing together the selector – shea Mar 19 '16 at 03:22