How can I select an element with multiple classes in jQuery?

How can I select an element with multiple classes in jQuery?

I want to select all the elements that have the two classes a and b.

<element class="a b">

So, only the elements that have both classes.

When I use $(".a, .b") it gives me the union, but I want the intersection.

 

回答1

If you want to match only elements with both classes (an intersection, like a logical AND), just write the selectors together without spaces in between:

$('.a.b')

The order is not relevant, so you can also swap the classes:

$('.b.a')

So to match a div element that has an ID of a with classes b and c, you would write:

$('div#a.b.c')

(In practice, you most likely don't need to get that specific, and an ID or class selector by itself is usually enough: $('#a').)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章