jQuery hasClass() - check for more than one class Ask Question

jQuery hasClass() - check for more than one class Ask Question

With:

if(element.hasClass("class"))

I can check for one class, but is there an easy way to check whether "element" has any of many classes?

I am using:

if(element.hasClass("class") || element.hasClass("class") ... )

Which isn't too bad, but I am thinking of something like:

if(element.hasClass("class", "class2")

Which unfortunately doesn't work.

Is there something like that?

ベストアンサー1

element.is('.class1, .class2')

works, but it's 35% slower than

element.hasClass('class1') || element.hasClass('class2')

JSperf チャートでは、.hasClass() が .is() よりも高速であることが示されています。

See also this jsbench.me test.

おすすめ記事