galengodis
galengodis

Reputation: 933

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

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>

Upvotes: 36

Views: 13215

Answers (4)

KhogaEslam
KhogaEslam

Reputation: 3056

i just found this thread, and i wanted to clarify that .is() is very slower than hasClass()

and i found other thread which discusses that.

So, if you care for performance or if you check for large number of elements it is preferred to use hasClass()

also you can check jsperf here.

enter image description here

Upvotes: 1

Ferran Basora
Ferran Basora

Reputation: 3147

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

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

Upvotes: 68

Lee Price
Lee Price

Reputation: 5212

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

   // Do something

}

Upvotes: 0

Andy Rose
Andy Rose

Reputation: 16974

You can use the hasClass function.

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

Upvotes: 1

Related Questions