2

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
5
  • 4
    You should do this via the stylesheet. (With clever use of stuff like the descendant combinator this could be as easy as setting one class on a common parent element.) Otherwise, yes, of course you will have to loop through the individual items. Commented Jun 9, 2016 at 12:38
  • 2
    if you are able to use jQuery you can do $(".classtoChange").css("font-family", "newFont"); Commented Jun 9, 2016 at 12:40
  • "without making a new CSS style rule" Why can you not use css? Commented Jun 9, 2016 at 12:46
  • Your script adds the style inline to each instance, which is inefficient considering you can just add the style via CSS in one place. Commented Jun 9, 2016 at 12:47
  • @guest271314 I'm trying to make a function to be applied to an existing page, so CSS on-load wouldn't work. I could add a <style> tag and apply it to the class that way, but I'm not sure what CSS rules may already be in place. Commented Jun 9, 2016 at 17:52

1 Answer 1

5

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

that's a good idea. loops through the stylesheet instead of the class elements, but it changes the existing class (if there). Thanks!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.