Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
487 views
in Technique[技术] by (71.8m points)

jquery - javascript - changing a class' style

I've been working with jQuery for a while, but now I want to write something in pure javascript and it's prooving to be challenging.. One of my biggest problems at the moment is that I haven't found a way to set/change styling for a class. This is not a problem for elements with id, but I want to change the styling for a group of elements with the same class and not just for one element with an id.. In jQuery I would just write:

$('.someClass').css('color','red')

Is there really no simple equivalence to this in pure js?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try the following

var all = document.getElementsByClassName('someClass');
for (var i = 0; i < all.length; i++) {
  all[i].style.color = 'red';
}

Note: As Cheery pointed out getElementsByClassName won't work in IE. The linked question has a nice way to work around this limitation


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...