6

Using vanilla javascript or prototype can someone show me how I could run a check to see if a class exists? For example I am adding a class called hideIt with this code :

var overlay = document.getElementById("overlay_modal");
overlay.className += " hideIt";

I also need a script that later can check to see if hideIt exists. I have tried things like :

if (overlay.className == "hideIt")

But that is no good. Any ideas?

0

4 Answers 4

6

Use a regexp. \b will match word boundaries (a space, a newline character, punctuation character or end of string).

var overlay = document.getElementById("overlay_modal");
if (overlay.className.match(/\bhideIt\b/)) 
{
    // frob a widget
}
Sign up to request clarification or add additional context in comments.

1 Comment

Best, cleanest and most widely supported answer! :)
6

You could use getElementsByClassName(), albeit this isn't supported in all browsers (not in IE < 9):

if (!document.getElementsByClassName('classname').length){
    // class name does not exist in the document
}

else {
    // class exists in the document
}

You could, depending on browser compatibility requirements, use querySelectorAll():

if (document.querySelectorAll('#overlay_modal.hideIt')) {
    // the element with id of overlay_modal exists and has the class-name 'hideIt'
}

References:

2 Comments

I still think using a regexp on the element's className is the best approach in this case, since they already have a reference to the element itself. Works in all browsers, no feature detection or shims needed.
I tend to agree, but since you'd already covered that angle it didn't seem right including that aspect in my own answer. I wasn't saying that either of these are the best ways, but instead presenting alternatives to those already posted.
3
var id = document.getElementById("id");
var classes = id.className.split(" ");
if(classes.indexOf("class_name") == -1)
{
}

Comments

3

Because the question asks for it here also is the Prototype way,

if (overlay.hasClassName('hideIt'))

Comments

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.