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

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

问题描述:

我想选择具有 ab 两个类的所有元素.

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.

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

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

如果你只想匹配具有both 类的元素(一个交集,就像一个逻辑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')

因此,要将 ID 为 adiv 元素与 bc 类匹配,您需要会写:

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