Check if a CSS class exists without jQuery
11,839
Solution 1
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
}
Solution 2
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:
-
Compatibility for
querySelectorAll
at Quirksmode. -
querySelectorAll()
at Mozilla Developer Network. -
getElementsByClassName()
at Mozilla Developer Network. - Compatibility for getElementsByClassName(), at Quirksmode.
Solution 3
var id = document.getElementById("id");
var classes = id.className.split(" ");
if(classes.indexOf("class_name") == -1)
{
}
Solution 4
Because the question asks for it here also is the Prototype way,
if (overlay.hasClassName('hideIt'))
Author by
Zac
Updated on June 28, 2022Comments
-
Zac about 2 years
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?
-
Matt Ball over 12 yearsI 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. -
Sikshya Maharjan over 12 yearsI 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.
-
MRVDOG almost 11 yearsBest, cleanest and most widely supported answer! :)