简体   繁体   中英

How can I list CSS selectors in a stylesheet based on properties?

I need to create a list of selectors from a stylesheet if it has the following properties in its declaration. I am specifically looking for a script to list all selectors in a stylesheet that contain all or some of the following properties in their declaration: float, width, margin, and padding. I would just go through each stylesheet manually but there are about 30 and they are really really long. Any ideas?

Try something like this:

var targetRules = ['float','width','margin-top','margin-right'/*,...*/];
var selectorList = [];
var sheets = document.styleSheets;
for(var i=0; i<sheets.length; ++i) {
    var rules = sheets[i].cssRules;
    for(var j=0; j<rules.length; ++j) {
        var styles = rules[j].style;
        for(var k=0; k<styles.length; ++k) {
            if(~targetRules.indexOf(styles[k])) {
                selectorList.push(rules[j].selectorText)
            }
        }
    }
}

If you want to be thorough, you can parse the CSS and pick out rules that have the declarations you desire. The AST looks like it would be pretty easy to traverse.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM