javascript - changing a class' style

2019-01-26 06:47发布

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?

5条回答
爷的心禁止访问
2楼-- · 2019-01-26 06:48

You can use selector library, for example Sizzle: http://sizzlejs.com/ but if you want pure JS that I guess you are stuck with getting all the elements, and then programatically "handpicking" the ones that have classes you are interested in using RegEx like this for example:

This is an equivalent of your JQuery oneliner:

for( i in document.all) document.all[i].className && /\bpost-text\b/g.test(document.all[i].className) && (document.all[i].style.color = "red")

:)

If you don't need it in one line you can make it faster (and much more readable):

var myClassName = "someClass";
var regexp  = RegExp("\\b"+myClassName+"\\b/g");
var elements = document.all;
for( i in elements){
  var this_element = elements[i];
  if(regexp.test(this_element.className){
    this_element.style.color = "red";
  }
}

If "for( i in object)" doesn't work for you, just use classic for loop "for(var i = 0; i < elements.length; i++)".

It could be 'beautified' a bit with the use of some slightly more advanced JS concepts (array function mappings, folding and such), which JS version are you coding agains? I guess it's not ECMA Script 5, right?

Also, check out this question/answer Get All Elements in an HTML document with a specific CSS Class

查看更多
疯言疯语
3楼-- · 2019-01-26 06:57
var all = document.getElementsByClassName('someClass');
for (var i = 0; i < all.length; i++) {
  all[i].className += " red"; 
}

For better coding style add another class to the elements with the code above and then use CSS to change the color of all elements like this:

.red {
  color:red;
}
查看更多
兄弟一词,经得起流年.
4楼-- · 2019-01-26 06:59

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

查看更多
干净又极端
5楼-- · 2019-01-26 06:59

You can use:

document.getElementById("MyElement").className = "NewClass";

to change the class of the element and then just define the style for that new class in your CSS file

查看更多
狗以群分
6楼-- · 2019-01-26 07:09

What you want to change is the style sheet, I guess? Thats possible in Javascript, see

I'm afraid there is no library for that, I really would like to see one...

查看更多
登录 后发表回答