0

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.

2
  • 1
    You mean if there is any element in the DOM that has the class you are looking for? Also can you elaborate on the "does not work" part? Commented Sep 27, 2012 at 20:35
  • Yes, and it returns an empty array even if the class is on the page. And to clarify cross-browser, I was thinking back to at least IE6 and the last 2-3 versions of other browsers. Just trying to get 99% of users. If it can fail gracefully, that's ok too. Commented Sep 27, 2012 at 20:41

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I think my issue was not checking for onload first, so it was not finding it. I'll have to find a workaround for that since my clients could already have an onload check on their page. Maybe something like this: webreference.com/programming/javascript/onloads/index.html
Thanks for the more fleshed out example and fiddle.
Ahh I hadn't thought of that, I assumed the part where you called the function was just an example of use, and was not actually called right after declaring the function. Glad I could help in some way :)
3

You can use querySelector method much like jQuery selectors

2 Comments

But it isn't cross-browser-versions :)
Ah, obviously I didn't make my point clearly enough: my question was regarding the fact that document.querySelector() and document.querySelectorAll() isn't fully-supported cross-browser (although it's far better supported than I previously though: Quirksmode Compatibility reference.
1

In HTML5 you can use document.querySelectorAll() with CSS3 selectors.

if (document.querySelectorAll('.the_class_name').length > 0) {
  doIt();
}

7 Comments

OP asked for a cross-browser solution. This obviously isn't.
How it isn't cross-browser? document.querySelector() and document.querySelectorAll() is supported by FF from 3.5, IE 8, Opera 10 and Webkit 3.2
@JanHančič Cross-browser isn't defined in black and white. CQQL's solution has decent browser support.
IE7&6 do not support it. Granted the OP did not define exactly which browsers need to be supported.
I was thinking back to at least IE6 and the last 2-3 versions of other browsers. Just trying to get 99% of users. If it can fail gracefully, that's ok too.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.