Home » Html » jQuery – How to check if element has any of these classes

jQuery – How to check if element has any of these classes

Posted by: admin November 29, 2017 Leave a comment

Questions:

Example:

How do I check if div #test has any of .a1 .a2 .a3 .a4 .a5 classes? With only one if-statment…

<div id="test" class="a1 a2 a5"></div>
Answers:

You could use the jQuery is function, checking all the classes that you want match.

$("#test").is(".a1,.a2,.a3,.a4,.a5")

Questions:
Answers:

You can use the hasClass function.

var test = $('#test');
if(test.hasClass('a1') || test.hasClass('a2') || test.hasClass('a3') ...) {
...
}

Questions:
Answers:
if ($("#test").hasClass("a1") || $("#test").hasClass("a2") || $("#test").hasClass("a3") || $("#test").hasClass("a4") || $("#test").hasClass("a5")) {

   // Do something

}