javascript - changing a class' style

var sheet = document.createElement('style')
sheet.innerHTML = ".someClass {color: red;}";
document.body.appendChild(sheet);

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/


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

  • javascript document.getElementsByClassName compatibility with IE

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

  • Quirksmode: Change CSS
  • Totally Pwn CSS with Javascript (in Internet Archive)
  • Is the only way to change a style to do it per-element in JavaScript? (possible duplicate)

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