jQuery hasClass() - check for more than one class

2019-01-04 18:54发布

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?

10条回答
Explosion°爆炸
2楼-- · 2019-01-04 19:15

use default js match() function:

if( element.attr('class') !== undefined && element.attr('class').match(/class1|class2|class3|class4|class5/) ) {
  console.log("match");
}

to use variables in regexp, use this:

var reg = new RegExp(variable, 'g');
$(this).match(reg);

by the way, this is the fastest way: http://jsperf.com/hasclass-vs-is-stackoverflow/22

查看更多
手持菜刀,她持情操
3楼-- · 2019-01-04 19:25
element.is('.class1, .class2')

works, but it's 35% slower than

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

enter image description here

If you doubt what i say, you can verify on jsperf.com.

Hope this help someone.

查看更多
爷的心禁止访问
4楼-- · 2019-01-04 19:26

How about this?

if (element.hasClass("class1 class2")
查看更多
啃猪蹄的小仙女
5楼-- · 2019-01-04 19:31

This worked for me:

$('.class1[class~="class2"]').append('something');
查看更多
冷血范
6楼-- · 2019-01-04 19:32

How about:

element.is('.class1, .class2')
查看更多
唯我独甜
7楼-- · 2019-01-04 19:35

filter() is another option

Reduce the set of matched elements to those that match the selector or pass the function's test.

$(selector).filter('.class1, .class2'); //Filter elements: class1 OR class2

$(selector).filter('.class1.class2'); // Filter elements: class1 AND class2
查看更多
登录 后发表回答