4

I have a series of divs that share a class for assorted reasons (and a number of divs that get created via code at other points).

I've tried to find answers, but all rely on the class being in the stylesheet (if there even is one), which is something that doesn't happen in this case or that alters existing elements instead of the rules themselves.

So I need to do something like...

var add_to_styles('myClassName');
myClassName.cssText = "color: red;"

And have all divs that get created (both before and after the script running) that have the class

<div class="myClassName">I should be red</div>

To come out with the rule change. But I haven't found anything like this.

lilHar
  • 1,735
  • 3
  • 21
  • 35
  • You may yet make changes directly to the stylesheet, but remember one option is to add a class to a root element shared by those classes, and then add a more specific CSS selector that only applies when both those classes are in place (eg `html.toggleStateIsOn .myClassName`) – Katana314 Apr 19 '16 at 20:40
  • 4
    You can add new with new rules (new or existing classes) and append it to body (so it will be read after other stylesheets). – Przemysław Melnarowicz Apr 19 '16 at 20:45
  • @whipdancer The answers presuppose the use of a stylesheet. I'm asking how to add styles independent of a stylesheet. – lilHar Apr 19 '16 at 20:47
  • @PrzemysławMelnarowicz Brilliant in it's directness and simplicity and feeling it should have been obvious and should totally do it. Throw it up as an answer and you'll get my vote. – lilHar Apr 19 '16 at 20:49

3 Answers3

2

You can add new <style></style> with new rules (new or existing classes) and append it to body (so it will be read after other stylesheets).

You can also target by specific parent (and don't modify other existing elements if you don't want to change all of them).

1

If you are using jQuery you can try to use .css() function.

https://jsfiddle.net/rixlabs/annt81df/1/ for some tests

$(".myClassName").css("color", "red");
rick
  • 1,869
  • 13
  • 22
-1

Try this one:

document.getElementByClassName('myClassName').style.color = "red";

or

document.getElementById('myIdName').style.color = "red";