36

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>
Kees C. Bakker
  • 32,294
  • 27
  • 115
  • 203
galengodis
  • 901
  • 1
  • 9
  • 18
  • Are there only 5 classes to be matched, or do you want to match any class in the form `aN` or `aNN` etc.? – a'r Nov 08 '11 at 11:07

4 Answers4

68

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

$("#test").is(".a1,.a2,.a3,.a4,.a5")
pimvdb
  • 151,816
  • 78
  • 307
  • 352
Ferran Basora
  • 3,097
  • 3
  • 19
  • 13
1

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

KhogaEslam
  • 2,528
  • 1
  • 20
  • 21
1

You can use the hasClass function.

var test = $('#test');
if(test.hasClass('a1') || test.hasClass('a2') || test.hasClass('a3') ...) {
...
}
Andy Rose
  • 16,770
  • 7
  • 43
  • 49
0
if ($("#test").hasClass("a1") || $("#test").hasClass("a2") || $("#test").hasClass("a3") || $("#test").hasClass("a4") || $("#test").hasClass("a5")) {

   // Do something

}
Lee Price
  • 5,182
  • 11
  • 34
  • 36