Skip to content

Instantly share code, notes, and snippets.

@mattslack
Last active September 14, 2017 15:08
Show Gist options
  • Save mattslack/8042446 to your computer and use it in GitHub Desktop.
Save mattslack/8042446 to your computer and use it in GitHub Desktop.
Count the number of CSS selectors used on a given page.Refactored from: http://stackoverflow.com/questions/5228459/selector-count-in-css
/*properties
cssRules, href, length, log, selectorText, split, styleSheets
*/
(function () {
"use strict";
var j = 0,
totalRules = 0,
totalSelectors = 0,
count_rules = function (styleSheet) {
var i, rules = styleSheet.cssRules,
totalSelectorsInStylesheet = 0;
if (rules !== null){
totalRules += rules.length;
for (i = 0; i < rules.length; i++) {
if (rules[i].selectorText) {
totalSelectorsInStylesheet += rules[i].selectorText.split(',').length;
}
}
console.log("Stylesheet", j, ":", styleSheet.href);
console.log("* Rules:", rules.length);
console.log("* Selectors:", totalSelectorsInStylesheet);
}
return totalSelectorsInStylesheet;
};
console.log(document.styleSheets.length);
while (j < document.styleSheets.length) {
totalSelectors += count_rules(document.styleSheets[j]);
j++;
}
console.log("Total selectors:", totalSelectors);
console.log("Total rules:", totalRules);
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment