Search code examples
javascriptundefinedstylesheet

Trying to read styleSheets returns undefined


I've searched for an answer and no solution seems to fix this problem, so hopefully stating it specifically will help me find a solution.

I'm trying to read cssText of the first stylesheet using document.styleSheets[0].cssText, but it always returns undefined. I do have a stylesheet and it's visibly noticeable, but JavaScript doesn't seem to recognize it.

This did, however, work when I included the stylesheet within the page using <style>. I don't see why this would change when using <link>, though. Not only is it placed before the script, but it even returns undefined when using javascript:alert(document.styleSheets[0].cssText) in the omnibar after the page is fully loaded.

Thanks for any help.

Edit: This applies to any method with document.styleSheets[0], including those of which are supposed to work on multiple browsers and have worked for me prior to using <link>. For example: document.styleSheets[0].cssRules[0].selectorText


Solution

  • According to quirksmode.org, document.styleSheets[n].cssText is only supported in IE.

    The form

    document.styleSheets[n].cssRules[m].cssText
    

    seems to be more widely supported, so you could just loop over that and build a string from the individual rules. (Although you have to replace cssRules with rules for IE).