Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I parse @import stylesheets with Javascript

Tags:

javascript

css

I am trying to read CSS selectors in my stylesheets with the document.styleSheets array. It works fine with <link> and <style> tags, but when I use @import inside a <style> it doesn't show up in the array - only as a cssRule (style is "Undefined" in Safari 3 and FF 3).

So: How can I parse the css in an @imported file?

like image 241
joolss Avatar asked Dec 21 '08 22:12

joolss


People also ask

Can you use CSS in JavaScript?

It's now possible to create CSSStyleSheet object from JavaScript. // Create our shared stylesheet: const sheet = new CSSStyleSheet(); sheet. replaceSync('#target {color: darkseagreen}'); // Apply the stylesheet to a document: document.

Can you use @import in CSS?

The @import rule allows you to import a style sheet into another style sheet. The @import rule must be at the top of the document (but after any @charset declaration). The @import rule also supports media queries, so you can allow the import to be media-dependent.


1 Answers

Assuming that our document contains an @import-rule as first rule in the first stylesheet, here's the code for standards compliant browsers

document.styleSheets[0].cssRules[0].styleSheet.cssRules;

and the special case for our all-beloved IE

document.styleSheets[0].imports[0].rules;

You could have easily figured this out yourself if you had read the page at quirksmode.org to which I had already linked and then walked the properties of the @import-rule with a for..in loop - that's what I did...

PS: I can't comment on other answers yet, but if I could, I would have ridiculed you properly ;)

like image 64
Christoph Avatar answered Nov 02 '22 05:11

Christoph