Is there any way to add css rules by javascript?

Asked

Viewed 78 times

6

If I have the following tag style:

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

It would be possible to add another new css rule like inside this style through the Javascript?

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

.class-x {
     color:yellow;
}
  • You can do it using a jQuery append, right? Half a Trash, but it works

  • 1

    Theoretically, you can use document.styleSheets but there’s probably a more practical way (with CSS hierarchy, maybe) of doing what you want. Can you explain better what the goal is? Or is it just curiosity?

  • 1

    What is the goal? Have some example that needs this logic?

  • @Gabe curiosity. Some do not see utility, but it is not a question of being useful. I just want to learn even if it has a form. After that comment someone must want to give me negatives :)

  • Thanks @Gabe! I found this in the reference you sent https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/insertRule

  • @Wallacemaxters I’ve never used, so I can’t say exactly what is possible to do or not. But I believe that dcument.styleSheets be really the way...

  • That would be: var myElements = Document.querySelectorAll(".bar"); for (var i = 0; i < myElements.length; i++) { myElements[i].style.opacity = 0; }

  • That’s not what @durtto

Show 3 more comments

1 answer

7


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

It is through the method insertRule, present in CSSStyleSheet.

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

In that case I’ll take the first:

var css = document.styleSheets[0]

Then we insert the rule in this style:

css.insertRule('body{ color: green; }', 0);
  • some time ago, I made use of the css.js, if you study its source code, you will see that it makes heavy use of this resource.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.