function gatherClasses() {
var tags = document.getElementsByTagName('*');
var cls, clct = {}, i, j, l = tags.length;
for( i = 0; i < l; i++ ) {
cls = tags[i].className.split(' ');
for( j = 0; j < cls.length; j++ ) {
if( !cls[j] ) continue;
clct[cls[j]] = 'dummy'; //so we only get a class once
}
}
cls = [];
for( i in clct ) {
cls.push( i );
}
return cls;
}
alert(gatherClasses())
这是一个带有正则表达式匹配的版本
function gatherClasses( matchString ) {
if( matchString ) {
var rxp = new RegExp( matchString );
} else {
var rxp = /.*/;
}
var tags = document.getElementsByTagName('*');
var cls, clct = {}, i, j, l = tags.length;
for( i = 0; i < l; i++ ) {
cls = tags[i].className.split(' ');
for( j = 0; j < cls.length; j++ ) {
if( !cls[j] || !rxp.test( cls[j] ) ) {
continue;
}
clct[cls[j]] = 'dummy'; //so we only get a class once
}
}
cls = [];
for( i in clct ) {
cls.push( i );
}
return cls;
}
//find classes that match 'stack'
alert(gatherClasses('stack'))