views:

474

answers:

1

Given a web page that has loaded (possibly several) CSS files, and inline styles, through the use of:

<link rel="stylesheet" type="text/css" href="some_file.css" />
<style type="text/css"> /* some css rules */  </style>
<link rel="stylesheet" type="text/css" href="some_other_file.css" />
<style type="text/css"> /* some other css rules */  </style>      
<!-- etc -->

How would one go about writing a function (possibly with jQuery) to extract all the net CSS rules in effect?

+3  A: 

I am not sure what you want to do with this, but this should get you started:

function getStyles() {
    if(!document.styleSheets) return false; // return false if browser sucks
    var rules = new Array();
    for (var i=0; i < document.styleSheets.length; i++) {
        var x = 0;
        styleSheet = document.styleSheets[i];
        if(styleSheet.cssText) { // if this is IE, get the rules directly
            rules.push(styleSheet.cssText);
        } else {
            // otherwise get them individually
            do {
                cssRule = styleSheet.cssRules[x];
                if(cssRule) rules.push(cssRule.cssText);
                x++;
            } while (cssRule);
        }
    }
    return rules;
}

When you call this it will return an array of all the rules. Tested in Firefox, IE.

Paolo Bergantino