I’m looking for a cross-browser compatible and lightweight way to check to see if any instance of a CSS class is on a page or not.
For example, if I want to check for ‘myclass’, and or was anywhere on the page, then it would return true, else false.
I’ve tried a function like this, but it does not work:
function getElementsByClassName( clsName )
{
var arr = new Array();
var elems = document.getElementsByTagName("*");
for ( var cls, i = 0; ( elem = elems[i] ); i++ )
{
if ( elem.className == clsName )
{
arr[arr.length] = elem;
}
}
return arr;
}
if ( getElementsByClassName('myclass').length >= 1) {
// yes, it's on the page
}
Thanks.
You could try something like this: http://jsfiddle.net/sK2zd/
I just changed your code a little, but it’s doing what you expect.
UPDATE:
Looking back at this answer I realized I never suggested
elems[i].className == clsNameprobably isn’t correct, as theclassNameproperty may be several classes separated by a space character. So there would need to be a better way to see if it has a class.