Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing a DIV class style in JavaScript [duplicate]

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

like image 752
Garfield Punchbag Avatar asked May 09 '13 11:05

Garfield Punchbag


2 Answers

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'
}
like image 195
monokh Avatar answered Sep 21 '22 19:09

monokh


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.

like image 42
Gurpreet Singh Avatar answered Sep 22 '22 19:09

Gurpreet Singh