Skip to content

Instantly share code, notes, and snippets.

@eltoob
Created January 21, 2013 15:09
Quick lines to get the number of selectors in each CSS to make sure that IE is not breaking
var
styleSheets = document.styleSheets,
totalStyleSheets = styleSheets.length;
for (var j = 0; j < totalStyleSheets; j++){
var
styleSheet = styleSheets[j],
rules = styleSheet.cssRules,
totalRulesInStylesheet = rules.length,
totalSelectorsInStylesheet = 0;
for (var i = 0; i < totalRulesInStylesheet; i++) {
if (rules[i].selectorText){
try{
totalSelectorsInStylesheet += rules[i].selectorText.split(',').length;
}
catch(err){
console.log(err);
}
}
}
console.log("Stylesheet: "+styleSheet.href);
console.log("Total rules: "+totalRulesInStylesheet);
console.log("Total selectors: "+totalSelectorsInStylesheet);
alert("Stylesheet: "+styleSheet.href + "\n" + "Total rules: "+totalRulesInStylesheet + "\n" + "Total selectors: "+totalSelectorsInStylesheet)
}
@elvin-lian
Copy link

There is a cool script. But it may have a bug:
TypeError: Cannot read property 'length' of null
when the page has CSS Style element.

var styleSheets = document.styleSheets,
        totalStyleSheets = styleSheets.length;
for (var j = 0; j < totalStyleSheets; j++) {
    var styleSheet = styleSheets[j],
            rules = styleSheet.cssRules,
            totalSelectorsInStylesheet = 0;

    var totalRulesInStylesheet = rules ? rules.length : 0;

    for (var i = 0; i < totalRulesInStylesheet; i++) {
        if (rules[i].selectorText) {
            try {
                totalSelectorsInStylesheet += rules[i].selectorText.split(',').length;
            }
            catch (err) {
                console.log(err);
            }
        }
    }
    console.log("Stylesheet: " + styleSheet.href);
    console.log("Total rules: " + totalRulesInStylesheet);
    console.log("Total selectors: " + totalSelectorsInStylesheet);
    alert("Stylesheet: " + styleSheet.href + "\n" + "Total rules: " + totalRulesInStylesheet + "\n" + "Total selectors: " + totalSelectorsInStylesheet)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment