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?
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?
Share Improve this question edited Dec 27, 2011 at 14:16 Rob W 349k87 gold badges807 silver badges682 bronze badges asked Dec 6, 2011 at 19:12 ZacZac 12.8k21 gold badges76 silver badges124 bronze badges 04 Answers
Reset to default 6Use 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
}
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.
var id = document.getElementById("id");
var classes = id.className.split(" ");
if(classes.indexOf("class_name") == -1)
{
}
Because the question asks for it here also is the Prototype way,
if (overlay.hasClassName('hideIt'))