Search code examples
javascriptjqueryhtmlcssjquery-1.3

Finding all classes that match a pattern in an HTML document?


I got to thinking today: what is the best way of getting a distinct (ie no repeats) list of classes used in a document that (preferably) match a pattern (regular expression) pattern or (alternatively) start with a certain character sequence? JQuery can be used for this or just straight Javascript.

Now it should obviously cater for all legal class usages, for example:

<div class="class1 class2 class3">
</div>

And I don't want to parse the document with regular expressions. That's simply too error prone. What I'm interested in is a Jaavascript solution that walks the DOM or uses something like jQuery to do that.

Oh this should also include any classes that have been dynamically added/removed through previous Javascript code.

Suggestions?


Solution

  • Using jQuery:

    var listClasses = function( pattern ){
        var allClassesTmp = {}, allClasses = []; 
        var rx = pattern ? (new RegExp(pattern)) : (new RegExp(".*"));
    
        $('*[class]').each( function(){ 
            var cn = this.className.split(/\s+/); 
            for(var i=cn.length;--i>-1;){ 
                if(rx.test(cn[i]))allClassesTmp[ cn[i] ] = 1 
            } 
        }); 
        for(var i in allClassesTmp)allClasses.push(i); 
        return allClasses;
    }