Is there any way to add css rules by javascript?

6

If I have the following tag style :

<style>
 body{
  color:red;
}
</style>

Would it be possible to add a new css rule as within that style through Javascript ?

For example, I want to add this to the end of the first style I gave as an example:

.class-x {
     color:yellow;
}
    
asked by anonymous 14.12.2015 / 17:54

1 answer

7

@Gabe gave a reference in which, after being tested, I verified that it works (at least on Google Chrome 46).

It is through the insertRule method, present in CSSStyleSheet .

To access it, you must access the list of elements style of the page.

In this case I'll get the first one:

var css = document.styleSheets[0]

Then insert the rule into this style :

css.insertRule('body{ color: green; }', 0);
    
14.12.2015 / 18:07