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
  • Does this answer your question? How to replace all occurrences of a string in JavaScript Commented Jul 15, 2021 at 15:37
  • 3
    @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. Commented Jul 19, 2021 at 0:36

11 Answers 11

57

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the new answer to an old question! Definitely much better with the built in method.
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/…
38

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.

Comments

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 Comments

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
Not a bug, @alexalex. I declare variables separated with commas. See stackoverflow.com/questions/11076750/… for more info
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 :)
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 Comments

This would be improved by testing for and using the built-in document.getElementsByClassName() method where present.
I'm getting issues in chrome & IE with this. chrome console has an error of "Cannot set property 'display' of undefined"
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 Comment

I was looking for this answer to give it an upvote!
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.

Comments

4

In modern JS, this one-liner will do:

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

Comments

1

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 Comments

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 :)
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.
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>

Comments

-1

jQuery solution is straightforward:

$(".className").hide();

1 Comment

OP asked for plain javascript.
-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 Comment

Consider using document.getElementsByClassName instead of piecing together the selector

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.