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?
The hasClass() is an inbuilt method in jQuery which check whether the elements with the specified class name exists or not. Syntax: $(selector). hasClass(className);
In vanilla JavaScript, you can use the contains() method provided by the classList object to check if any element contains a specific CSS class. This method returns true if the class exists, otherwise false .
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
}
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:
querySelectorAll
at Quirksmode.querySelectorAll()
at Mozilla Developer Network.getElementsByClassName()
at Mozilla Developer Network.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With