开发者

Listing known CSS classes using Javascript

I'm trying to find a good way to collect the names of classes defined in the stylesheets included with a given document. I know about document.StyleSheetList but it doesn't seem like it'd be easy to parse. What I'm looking for is something like, for a stylesheet document such as:

.my_class { 
    ba开发者_JAVA技巧ckground: #fff000; 
}
.second_class {
    color: #000000;
}

I could extract an array like ["my_class", "second_class"]. This obviously assumes the favorable scenario of a fully loaded dom and stylesheets.

I've been looking everywhere for a good way to do something like this and so far, have made little progress. Does anyone have any idea about how to pull this off? Thanks!


This will show all rules defined in the stylesheets.

var allRules = [];
var sSheetList = document.styleSheets;
for (var sSheet = 0; sSheet < sSheetList.length; sSheet++)
{
    var ruleList = document.styleSheets[sSheet].cssRules;
    for (var rule = 0; rule < ruleList.length; rule ++)
    {
       allRules.push( ruleList[rule].selectorText );
    }
}

The thing, though, is that it includes all rules regardless of being class or tag or id or whatever..

You will need to explain in more detail what you want to happen for non class rules (or combined rules)


You were on track with document.styleSheets (https://developer.mozilla.org/en/DOM/document.styleSheets)

https://developer.mozilla.org/en/DOM/stylesheet.cssRules

Here's a quick and dirty method to output all class selectorTexts to the console in Firefox + Firebug.

    var currentSheet = null;
    var i = 0;
    var j = 0;
    var ruleKey = null;

    //loop through styleSheet(s)
    for(i = 0; i<document.styleSheets.length; i++){
        currentSheet = document.styleSheets[i];

        ///loop through css Rules
        for(j = 0; j< currentSheet.cssRules.length; j++){

            //log selectorText to the console (what you're looking for)
            console.log(currentSheet.cssRules[j].selectorText);

            //uncomment to output all of the cssRule contents
            /*for(var ruleKey in currentSheet.cssRules[j] ){
                 console.log(ruleKey +': ' + currentSheet.cssRules[j][ruleKey ]);
            }*/
        }
    }


This is probably not something you really want to be doing except as part of a refactoring process, but here is a function that should do what you want:

function getClasses() {
    var classes = {};
    // Extract the stylesheets
    return Array.prototype.concat.apply([], Array.prototype.slice.call(document.styleSheets)
        .map(function (sheet) {
            if(null == sheet || null == sheet.cssRules) return;
            // Extract the rules
            return Array.prototype.concat.apply([], Array.prototype.slice.call(sheet.cssRules)
                .map(function(rule) {
                    // Grab a list of classNames from each selector
                    return rule.selectorText.match(/\.[\w\-]+/g) || [];
                })
            );
        })
    ).filter(function(name) {
        // Reduce the list of classNames to a unique list
        return !classes[name] && (classes[name] = true);
    });
}


What about

.something .other_something?

Do you want a pool of classNames that exist? Or a pool of selectors?

Anyway, have you tried iterating through document.styleSheets[i].cssRules? It gives you the selector text. Parsing that with some regexp kungfu should be easier...

Do you need it to be crossbrowser?


You can accompish this with jQuery. Example would be

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script>
  $(document).ready(function(){
      var allobjects = $("*")
  });
</script>

Check out the jQuery website: http://api.jquery.com/all-selector/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜