36

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?

4
  • This may be useful: stackoverflow.com/questions/1933602/…
    – IsisCode
    Commented Feb 24, 2012 at 18:38
  • @Cheery not a duplicate. The OP explicitly wants a non-jquery answer.
    – JaredPar
    Commented Feb 24, 2012 at 18:40
  • @JaredPar Sorry, did not read very carefully.
    – Cheery
    Commented Feb 24, 2012 at 18:44
  • See my edit below. You can just wrap it and make it into a function.
    – nana
    Commented Feb 24, 2012 at 20:03

6 Answers 6

49

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

3
  • IE before 9 does not support it. stackoverflow.com/questions/7410949/…
    – Cheery
    Commented Feb 24, 2012 at 18:43
  • Or even "for(i in all)", at least I believe it works in non strict mode too.
    – nana
    Commented Feb 24, 2012 at 18:44
  • 1
    It is good but it won't update if next element with that class will be created. Right ? Commented Jul 5, 2013 at 19:51
31

I find it easier to use CSS variables. You can set the class to use a variable and then change that value in Javascript, thus changing the CSS.

If you style the class like:

:root {
    --some-color: red;
}

.someClass {
    color: var(--some-color);
}

Then you can change the variable's value in Javascript with

document.documentElement.style.setProperty('--some-color', '(random color)');

(random color) can then be anything that would be considered a valid CSS color (eg. blue, black, #626262, rgb(12, 93, 44))

Updating the value in JS automatically updates the page as well.

And of course, this can be done with any property, not just color. Here is an example that changes the padding of a class:

CSS

:root {
    --some-padding: 12px;
}

.someClass {
    padding: var(--some-padding);
}

Javascript

// Set padding to 15px
document.documentElement.style.setProperty('--some-padding', '15px');

// Set padding to 5rem
document.documentElement.style.setProperty('--some-padding', '5rem');

// Set padding to 25%
document.documentElement.style.setProperty('--some-padding', '25%');

Useful example: toggle dark / light mode:

(How to use css properties to dynamically set css properties)

// set to light mode:
document.documentElement.style.setProperty('--bg-color', getComputedStyle(document.documentElement).getPropertyValue('--bg-color-light'));

// set to dark mode:
document.documentElement.style.setProperty('--bg-color', getComputedStyle(document.documentElement).getPropertyValue('--bg-color-dark'));

With the respective css:

:root {
  --bg-color: black;
  --bg-color-light: white;
  --bg-color-dark: black;

body {
  background-color: var(--bg-color);
}

Sources

How to declare and use CSS variables: https://www.w3schools.com/css/css3_variables.asp
How to update a CSS variable in JS: https://css-tricks.com/updating-a-css-variable-with-javascript/

4
  • 2
    Genius!! Should be marked as the best answer.
    – Fabio
    Commented Mar 4, 2021 at 17:58
  • 1
    The best ans superior answer by far. Do not mess with pesky for cycles, when you can use variables inside the CSS...
    – Brethlosze
    Commented Apr 28, 2021 at 5:31
  • Great answer! PS: I think you done a typo. The variable name is «--some-padding» inside the css section, but it's «--some-color» inside the javascript section. Commented Nov 2, 2021 at 11:16
  • @LucioMenci you're absolutely correct, I edited the answer. Thx
    – elialm
    Commented Nov 3, 2021 at 13:16
9
var sheet = document.createElement('style')
sheet.innerHTML = ".someClass {color: red;}";
document.body.appendChild(sheet);
3

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...

2
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;
}
1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.