2

Using javascript, I want to change the style of class .s into

.s {
  display: block;
}

Why this cannot work:

document.getElementsByClassName('s').style.display='block';
Praveen
  • 55,303
  • 33
  • 133
  • 164
Yishu Fang
  • 9,448
  • 21
  • 65
  • 102
  • Why not create a class for the new styles and append this new class to all of the matching classes? – Joshua Smickus Jan 06 '14 at 09:14
  • @JoshSmickus, those lines are used in the response code of a checkbox. I want to use that checkbox to control if some elements should be shown. – Yishu Fang Jan 07 '14 at 01:57
  • So, you could write: `var elems = document.getElementsByClassName('s'); for(var i = 0; i < elems.length; i++) { elems[i].className += " new-class"; }` Then define new-class with appropriate styles – Joshua Smickus Jan 07 '14 at 09:36
  • @JoshSmickus, What I really want to say is: because of "...", I don't think it is appropriate to "create a class for the new style and ..." – Yishu Fang Jan 08 '14 at 08:07
  • What? :S I don't get what you mean? – Joshua Smickus Jan 08 '14 at 10:31
  • @JoshSmickus. I mean, I don't think it is appropriate to "create a class for the new style and ..." for my situation. – Yishu Fang Jan 09 '14 at 06:15

3 Answers3

21

document.getElementsByClassName: returns a set of elements which have all the given class names.

You may have multiple elements with this class name. so you need to provide index like

document.getElementsByClassName('s')[0].style.display='block';

Inorder to apply for style for all elements with same class name:

var ele = document.getElementsByClassName('s');
for (var i = 0; i < ele.length; i++ ) {
    ele[i].style.display = "block";
}
Praveen
  • 55,303
  • 33
  • 133
  • 164
0

As getElementsByClassName returns an array you need to make a for loop over all found elements:

var elements = document.getElementsByClassName('s');
for (var i = 0; i < elements.length; i++) {
    elements[i].style.display = "block";
}
RononDex
  • 4,143
  • 22
  • 39
-1
var sCls = document.getElementsByClassName('s');
for(var i in sCls) {
    sCls[i].style.display='block';
}

this may work!

jingyinggong
  • 636
  • 5
  • 9