Reputation:
I want to use CSSStyleSheet.insertRule() to insert a new class inside a specific stylesheet. That stylesheet has the id "customStylesheet" for example.
This page says "A specific style sheet can also be accessed from its owner object (Node or CSSImportRule), if any.". However I can't figure out how to access that specific stylesheet.
Upvotes: 0
Views: 166
Reputation: 2984
It is fairly straight forward.
var sheet = document.getElementById('customStylesheet').sheet;
sheet.insertRule('.someclass {display: none;}'); // was missing a ' here
Here is a fiddle showing it working. I have updated the fiddle to show it working on a style tag in the head also.
Upvotes: 3
Reputation: 1528
To get a styleSheet by ID, use this:
document.getElementById('stylesheet').sheet;
Upvotes: 0
Reputation: 1528
This can be done with no jQuery. Say that you wished to set everything with the class purpleText
to color: purple
. First, you would get the stylesheet using document.styleSheets[_index_].ownerNode.sheet
. Next, use the insertRule()
method. The parameter is just a string holding the CSS code, as in ".purpleText{color: purple}"
. So, for the first stylesheet, the whole command would be document.styleSheets[0].ownerNode.sheet.insertRule(".purpleText{color: purple}");
Upvotes: 0