user1734974
user1734974

Reputation:

How to add a class to a specific stylesheet?

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

Answers (3)

gforce301
gforce301

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

rydwolf
rydwolf

Reputation: 1528

To get a styleSheet by ID, use this:

document.getElementById('stylesheet').sheet;

Upvotes: 0

rydwolf
rydwolf

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

Related Questions