Reputation: 183
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.
Upvotes: 0
Views: 135
Reputation: 50905
You could try something like this: http://jsfiddle.net/sK2zd/
I just changed your code a little, but it's doing what you expect.
function getElementsByClassName(clsName) {
var arr = [];
var elems = document.getElementsByTagName("*");
for (var i = 0; i < elems.length; i++) {
if (elems[i].className == clsName) {
arr.push(elems[i]);
}
}
return arr;
}
window.onload = function () {
var all_classes = getElementsByClassName('testing');
if (all_classes.length > 0) {
// yes, it's on the page
alert("Found " + all_classes.length + " element(s) with class 'testing'");
} else {
alert("Found none");
}
};
UPDATE:
Looking back at this answer I realized I never suggested elems[i].className == clsName
probably isn't correct, as the className
property 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.
Upvotes: 3
Reputation: 1356
In HTML5 you can use document.querySelectorAll() with CSS3 selectors.
if (document.querySelectorAll('.the_class_name').length > 0) {
doIt();
}
Upvotes: 1