0

so I have this CSS:

.cormes{
  font-size: 30px;
  margin-bottom: 10px;
  text-align: centre;
  }

I need to make that disappear and appear using javascript. I know you can use style.display='none' and style.display='inline-block' for normal ones. I don't know how to do this for classes. Please help

3 Answers3

1

If you want to affect all elements with a class you have to loop in them:

var elems = document.getElementsByClassName('cormes');
for (var i = 0; i < elems.length; i++ ) {
    elems[i].style.display = "none";
}

More info about this here: https://stackoverflow.com/a/20946374/7919626

Word Rearranger
  • 1,306
  • 1
  • 16
  • 25
0

either you assign a class which is invisible or you add a new style to a existing class. Usually its not a good idea to redefine css classes due side effects. For the sake of showing you something new i use the visibility css rule. Display : "none" would do the same. This new class i would add either hard coded in the css or by js.

 .cormes_invisible{visibility:hidden;}

Now all you has to do is to simply change the class name. I add "_invisible" so its rather trivial to restore the original class later one by using the split function. So there is nothing complicated or strange in it :)

      function makeinvisible(id){
       var element=document.getElementById(id)
        try { // rather brutal way
          element.classList.remove("cormes");
          } catch (ex){}
          element.classList.add("cormes_invisible");
   }    

        function makevisible(id){
       var element=document.getElementById(id)
        try { // rather brutal way
          element.classList.remove("cormes_invisible");
          } catch (ex){}
          element.classList.add("cormes");
      }

another way would be to add a style attribute with the invisible css. and remove it afterwards. There are a few posiibilitys. (And alot of very nice tutorials in the web ;))

btw: the other classic way would be :

      var elements =document.getElementsByClassName("cormes");

      for (i=0;i<elements.length;i++){
       try { // rather brutal way
          elements[i].classList.remove("cormes");
          } catch (ex){}
          elements[i].classList.add("cormes_invisible");
      }
Thomas Ludewig
  • 696
  • 9
  • 17
0

First get the classes wrapped in the HTMLCollection, and then hide each one with with a forEach

const elements = document.getElementsByClassName('cormes');
Array.prototype.forEach.call(elements, element => element.style.display = 'none');

The same with ...display = 'initial', if we want to show them again. Would be useful to create a function for easily show and hide the cormes.

function showCormes(show) {
  const styleValue = show ? 'initial' : 'none';
  Array.prototype.forEach.call(elements, element => element.style.display = styleValue);
}

So we can easily show and hide that way:

showCormes(true);
showCormes(false);
BBM
  • 31
  • 3