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?
Mr. Polywhirl
49.1k12 gold badges95 silver badges147 bronze badges
asked Jun 9, 2016 at 12:37
1 Answer 1
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>
potashin
44.7k11 gold badges92 silver badges113 bronze badges
answered Jun 9, 2016 at 12:46
1 Comment
freginold
that's a good idea. loops through the stylesheet instead of the class elements, but it changes the existing class (if there). Thanks!
lang-js
css
?