tags:

views:

1045

answers:

3

Hi! 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?

+7  A: 

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 ;)

Christoph
Go ahead =) (slapping my own forehead) I thought I had checked the properties but I must have made a mistake somewhere. Thanks mate!
joolss
@Christoph: Now you can comment ;)
some
+1  A: 

Check this page - which further links to this one on quirksmode.org.

Thanks, but I have tried that... the Quirksmode examples never parse stylesheets embedded with @import.

If I have this HTML/CSS:

<link rel="stylesheet" type="text/css" href="css/test1.css" />

<style type="text/css">

    @import url('css/test2.css');

    div {
        color: blue;
    }

</style>

... then document.styleSheets.length is 2 (the link tag and the style tag). The CSS file that is linked through @import will be available as

document.styleSheets[1].cssRules[0].

In other words, a CSS rule. This can also be seen at the Quirksmode page that you mentioned, Christoph. I can get its cssText ("@import url('css/test2.css');") but I can't figure out how to parse the CSS inside the file (test2.css)...

If I have totally missed something obvious here, feel free to ridicule me... :)

joolss
+1  A: 

Excellent page with lots of stylesheet parsing info: http://www.howtocreate.co.uk/tutorials/javascript/domstylesheets

joolss