如何在jQuery中选择具有多个类的元素?

如何在jQuery中选择具有多个类的元素?

问题描述:

我想选择所有具有两个类 a b 的元素。

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

<element class="a b">

因此,只有两个类的元素。

当我使用 $(。a,.b)时,它给了我联盟,但我想要交集。

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

如果你只想匹配两个类的元素(交集,就像逻辑AND) ,只需将选择器一起写成不含空格

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')

所以要匹配一个 div 元素,其元素 a ,类 b c ,你会写:

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

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

(实际上,你很可能不喜欢不需要特定的,并且ID或类选择器本身就足够了: $('#a' )。)

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