Categories
css html htmlelements jquery jquery-selectors

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

2217

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.

3

  • 2

    It would be nice if you could define what union and intersection means for us newbs 🙂

    Apr 13, 2016 at 3:22

  • 10

    @KolobCanyon union and intersection are basic set theory concepts. So for instance a union would be all French speakers (includes both men and women), whereas an intersection would be all women who speak French (excludes everyone who does not speak French, and excludes all people who are not women). Unions and intersections can be made with any number of characteristics defining each set. en.wikipedia.org/wiki/Union_(set_theory) en.wikipedia.org/wiki/Intersection_(set_theory)

    Jul 25, 2016 at 16:04

  • 7

    I think you mean that of the two sets “women” and “French-speakers”, the union would be all the women in the world and all the French-speakers in the world, a set that includes both women who don’t speak French and French-speaking men. The intersection is, as you wrote, only those women who speak French.

    Sep 8, 2016 at 11:24


2810

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

2

  • 10

    @Flater: It was just for the sake of example. But it might be useful if the classes b and c are dynamically added, and you only want to select the element if it has those classes.

    Aug 7, 2012 at 17:19


  • 35

    @Shimmy: Yes. A space between two selectors means you’re searching for descendants; i.e. .a .b searches for elements with class b that are descendants of an element with class a. So something like div a will only return a elements that are inside a div element.

    May 12, 2013 at 23:49


181

You can do this using the filter() function:

$(".a").filter(".b")

2

  • 16

    What is the difference between this answer and the accepted one?

    Aug 9, 2011 at 14:32

  • 50

    @Rice: This one will be a little bit slower, because it will build a list of objects with class “a” first, then remove all but those that have class “b”, whereas mine does this in one step. But otherwise, no difference.

    Sep 8, 2011 at 9:39

137

For the case

<element class="a">
  <element class="b c">
  </element>
</element>

You would need to put a space in between .a and .b.c

$('.a .b.c')

0