Javascript - class style change

I worked with jQuery for a while, but now I want to write something in pure javascript, and it will not be easy. One of my biggest problems at the moment is that I did not find a way to set / change the style for the class. This is not a problem for elements with id, but I want to change the style for a group of elements with the same class, and not just for one element with an identifier. In jQuery, I would just write:

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

Does it have simple equivalence in pure js?

+8
javascript jquery css class
source share
5 answers

Try to execute

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

Note. As Jerry noted, getElementsByClassName will not work in IE. A related question has a good way around this limitation.

  • javascript document.getElementsByClassName compatibility with IE
+12
source share
 var all = document.getElementsByClassName('someClass'); for (var i = 0; i < all.length; i++) { all[i].className += " red"; } 

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

 .red { color:red; } 
+2
source share

You can use a selector library, for example Sizzle: http://sizzlejs.com/ , but if you want pure JS, I think you're stuck with getting all the elements, and then programmatically โ€œpick upโ€ those that have classes that Are you interested in using RegEx, for example:

This is the 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 on one line, you can do 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 the object) " does not work for you, just use the classic for the loop " for (var i = 0; i <elements.length; i ++) ".

It can be โ€œdecoratedโ€ a bit using slightly more advanced JS concepts (array function comparisons, folding, etc.), in which version of JS are you encoding again? I think this is not ECMA Script 5, right?

Also check this question / answer Get all elements in an HTML document with a specific CSS class

+1
source share

What do you want to change, this is a stylesheet, I think? This is possible in Javascript, see

I am afraid that there is no library for this, I really would like to see it ...

+1
source share

You can use:

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

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

0
source share

All Articles