Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a CSS class exists without jQuery

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?

like image 222
Zac Avatar asked Dec 06 '11 19:12

Zac


People also ask

How do you check the class is exist or not in jQuery?

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);

How do I know if a CSS class is applied?

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 .


2 Answers

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
}
like image 119
Matt Ball Avatar answered Oct 06 '22 00:10

Matt Ball


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.
like image 34
David Thomas Avatar answered Oct 05 '22 23:10

David Thomas