I know document.styleSheets
which consists of all valid style sheets in a page. I want to know whether I can create a new one and append it to present list via JavaScript.
I have tried document.styleSheets[0].constructor
, document.styleSheets[0].__proto__.constructor
, new CSSStyleSheet
, CSSStyleSheet()
, and all I get from Chrome is:
TypeError: Illegal constructor.
CSSStyleSheet.constructor()
returned a pure object but I expect a CSSStyleSheet object.
I know I can create a link/style element and append it, then modify it. Can I create such objects directly with JavaScript?
As far as I know, the only approach that comes close to what you're asking for is the IE-only document.createStyleSheet([url] [,index])
method which you can use to create up to 31* styleSheet
objects (after which you'll still need to manually create style
elements and append them to document
).
This answer shows how you can define the createStyleSheet()
method for non-IE browsers but as you'd expect it does so by appending link
/style
elements (which for some reason you're trying to avoid).
* IE 6 to 9 is limited to 31 imported stylesheets due to 5-bit field used for storing sheet IDs. In IE10 this limit has been raised to 4095.