最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to change the style of elements with same class name - Stack Overflow

programmeradmin3浏览0评论

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';

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';
Share Improve this question edited Jan 6, 2014 at 9:09 Praveen 56.5k35 gold badges136 silver badges165 bronze badges asked Jan 6, 2014 at 9:02 Yishu FangYishu Fang 9,95822 gold badges66 silver badges108 bronze badges 6
  • Why not create a class for the new styles and append this new class to all of the matching classes? – user632287 Commented Jan 6, 2014 at 9: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 Commented Jan 7, 2014 at 1: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 – user632287 Commented Jan 7, 2014 at 9: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 Commented Jan 8, 2014 at 8:07
  • What? :S I don't get what you mean? – user632287 Commented Jan 8, 2014 at 10:31
 |  Show 1 more comment

3 Answers 3

Reset to default 22

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";
}

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";
}
var sCls = document.getElementsByClassName('s');
for(var i in sCls) {
    sCls[i].style.display='block';
}

this may work!

发布评论

评论列表(0)

  1. 暂无评论