Fred Oliveira
Fred Oliveira

Reputation: 531

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 { 
    background: #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!

Upvotes: 14

Views: 9556

Answers (5)

Prestaul
Prestaul

Reputation: 85145

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, making sure a selectorText exists (will throw errors otherwise on Media Queries)
                    return (rule.selectorText && rule.selectorText.match(/\.[\w\-]+/g)) || [];
                })
            );
        })
    ).filter(function(name) {
        // Reduce the list of classNames to a unique list
        return !classes[name] && (classes[name] = true);
    });
}

Upvotes: 3

Jason Benson
Jason Benson

Reputation: 3399

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 ]);
            }*/
        }
    }

Upvotes: 4

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196002

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)

Upvotes: 25

Austin Ginder
Austin Ginder

Reputation: 516

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/

Upvotes: -2

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?

Upvotes: 0

Related Questions