5

i can do this to change the style of a div ID...

document.getElementById('test').style.display = "none";

why can't i do this to do the same thing to a class?

document.getElementsByClassName('egg').style.display = "none";

How do I change the style of a class?

Thanks

  • 3
    Because `getElementsByClassName()` returns an array of elements, not a single element. – JJJ May 09 '13 at 11:08

5 Answers5

10

document.getElementsByClassName returns a list of elements with the class specified. You can set the display to none of the first element:

document.getElementsByClassName('egg')[0].style.display = "none";

Or loop through the list and set each to the desired effect:

var eggs = document.getElementsByClassName('egg');
for(var i = 0; i < eggs.length; i++) { 
  eggs[i].style.display='none'
}
monokh
  • 1,970
  • 3
  • 22
  • 31
2

This should work:

 var elements = document.getElementsByClassName('egg');
    for(var i = 0, length = elements.length; i < length; i++) {
         elements[i].style.display = 'none';
    }
}

Note: elements is an array, this code loops through it and sets each element style to none.

Gurpreet Singh
  • 20,907
  • 5
  • 44
  • 60
1

The return value of document.getElementsByClassName('egg') is an array.

document.getElementsByClassName('egg').forEach(function(b) {
        b.style.display = "none";
    })
Jan Turoň
  • 31,451
  • 23
  • 125
  • 169
Parv Sharma
  • 12,581
  • 4
  • 48
  • 80
  • 3
    It's an `HTMLCollection`, actually. It's generally usable like an array, but it's live (as in, if you removed the `egg` class from an element, it would magically disappear from the list). – cHao May 09 '13 at 11:15
  • However, you can use `Array.prototype.forEach.call(document.getElementsByClassName('egg'),function(b) {...});` – Jan Turoň May 09 '13 at 11:22
0
<script language="javascript">
function assignStyle() {
  var chks = document.getElementsByClassName('myClass');
  for (var i = 0; i < chks.length; i++) {
    chks[i].style.display = 'none';

  }

 }
 </script>

Happy Coding :)

dreamweiver
  • 6,002
  • 2
  • 24
  • 39
-1

insted of doing all this stuff simply use jquery $('.myClass').css({ ...Your CSS properties here... });

Ganesh Bora
  • 1,133
  • 9
  • 17