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?
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:
:)
If you don't need it in one line you can make it faster (and much more readable):
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
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:
Try the following
Note: As Cheery pointed out
getElementsByClassName
won't work in IE. The linked question has a nice way to work around this limitationYou can use:
to change the class of the element and then just define the style for that new class in your CSS file
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...