freginold
freginold

Reputation: 3956

Apply CSS change to a whole class at once with JavaScript

I want to make a change to all elements in a class using JavaScript.

Currently it looks like this:

var elements = document.getElementsByClassName(classToChange);

for (var i = 0; i < elements.length; i++) {
    elements[i].style.fontFamily = newFont;
}

My question is, is there a way to apply the new CSS property to the entire class at once (without making a new CSS style rule) or can it only be done by looping through the elements individually?

Upvotes: 2

Views: 1091

Answers (1)

Nenad Vracar
Nenad Vracar

Reputation: 122057

You can change or add new css rules with Javascript like this

var style = document.styleSheets[0].cssRules || document.styleSheets[0].rules;
for (var i = 0; i < style.length; i++) {
  if (style[i].selectorText == '.classToChange') {
    style[i].style['font-size'] = '50px';
  }
}
.classToChange {
  color: blue;
}
<p class="classToChange">Lorem</p>

Upvotes: 5

Related Questions