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 usin开发者_JAVA百科g <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
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).
I thing that this answer is out of time, but it could be useful for someone else. The result can be "undefined" due 2 different reasons:
a) In some browsers, the property "cssRules" does not work (in accord with http://www.javascriptkit.com/domref/cssrule.shtml, only for supported in NS/ Firefox). For the other browser, you should use the property "rules", instead.
You can solve the problem using something like:
if (document.styleSheets[0].cssRules)
crossrule=document.styleSheets[0].cssRules[0]
else if (document.styleSheets[0].rules)
crossrule=document.styleSheets[0].rules[0]
to extract the rule and, afterwards, to extract the name of selector:
document.styleSheets[0].cssRules[0].selectorText
b) After the overpassing of the issue a), you may have another problem: The rules that starts with a @, like @import of @font-face, as considered as rules. However, their "selectorText" is undefined. So, you must have a way of skip them. I am working on it, right now. But I have not found yet a solution. Anyway, it is an help to know way it is happening.
Hope this helps
精彩评论