Document. styleSheets stores a set of all CSS rules on the current page. You can traverse all the selectors defined in the <style> page and access the selectorText attribute to obtain the matching rules of the selector. Then, pass the rule to document. querySelectorAll to obtain the list of elements matching the rule on the page.
Here we only need to calculate the coverage of CSS rules, so we can access querySelectorAll (). length. By sorting, we can see the usage of each CSS.
The code is simple.
Copy codeThe Code is as follows: var usage = [];
Var sheets = document. styleSheets;
For (var I = sheets. length-1; I! =-1; I --){
Var rules = sheets [I]. rules;
For (var j = rules. length-1; j! =-1; j --){
Var rule = rules [j];
Var text = rule. selectorText;
Usage. push ({name: text, count: document. querySelectorAll (text). length });
}
}
Usage. sort (function (a, B) {return a. count-B. count });
For (var I = usage. length-1; I! =-1; I --){
Console. log ("selector:" + usage [I]. name + "\ n \ t matching count:" + usage [I]. count );
}
Call F12 and paste the code to the console and press Enter.
Of course, due to permission issues, CSS imported externally cannot be accessed in any way. If the broken IE of styleSheets is not supported, you can use expression or behaviour. htc to try it another day.
By the way, paste a test result: