Forum Moderators: not2easy

Message Too Old, No Replies

Access the cssTEXT of an imported style!

         

binja

7:45 pm on Dec 2, 2008 (gmt 0)

10+ Year Member



Hi..of course I'm new to CSS.. I have imported a style sheet and now I want to print all of the rules.

For NON-imported styles I use this..

document.write(document.styleSheets[0].cssRules[0].cssText)

and it nicely prints out the style. However , the second style sheet comes from an import so

document.write(document.styleSheets[1].cssRules[0].cssText)

just prints out

@import url(http://www.example.com/css/newmain.css);

How do I see the styles in the import? I tried to use ownerRule and parentStyleSheet but neither worked. Below are failed attempts. I'm using Firefox- Help please!

document.styleSheets[0].parentStyleSheet.cssRules[0].cssText
document.styleSheets[0].ownerRule.cssText
document.styleSheets[0].ownerRule[0].cssText

[edited by: tedster at 10:00 pm (utc) on Dec. 2, 2008]
[edit reason] use example.com, please see forum charter [/edit]

swa66

9:52 pm on Dec 2, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I typically use the web developer toolbar add-on of firefox (it's got a few easy entries in its css menu: "view css" (see it all) and "view style information" (see the css of what you click on). Firebug is another add-on for firefox that will show you the css (and even allow you much more interactively)
Alternatively, just surf to the css with your browser, it'll show you the source without much more.

binja

5:58 pm on Dec 7, 2008 (gmt 0)

10+ Year Member



Found the answer.. If you want to get the styles in the imported stylesheet, you need to recursively access it. Use cssRules[j].styleSheet to get the imported tree

var CSSAsString="";
function extractCSS() {

var i;
for (i=0;i<document.styleSheets.length;i++) {
processSheet(document.styleSheets[i]);
}
return CSSAsString;
}

function processSheet(theStyleSheet) {

var j;
for (j=0;j<theStyleSheet.cssRules.length;j++) {
if(!theStyleSheet.cssRules[j].selectorText) {
CSSAsString += "/* :::::" + theStyleSheet.cssRules[j].cssText + " ::::: */";
// this is an import file...recurse through it
//CSSAsString += theStyleSheet.cssRules[j].styleSheet.cssRules[0].cssText ;
processSheet(theStyleSheet.cssRules[j].styleSheet);

} else {
// add the style to the string
CSSAsString += theStyleSheet.cssRules[j].cssText + "\n" ;
}
}

}
extractCSS();