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.

10/22/2019 1:22:19 PM

Accepted Answer

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:


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


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


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

11/25/2018 9:26:57 PM

You can do this using the filter() function:


For the case

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

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

$('.a .b.c')

The problem you're having, is that you are using a Group Selector, whereas you should be using a Multiples selector! To be more specific, you're using $('.a, .b') whereas you should be using $('.a.b').

For more information, see the overview of the different ways to combine selectors herebelow!

Group Selector : ","

Select all <h1> elements AND all <p> elements AND all <a> elements :

$('h1, p, a')

Multiples selector : "" (no character)

Select all <input> elements of type text, with classes code and red :


Descendant Selector : " " (space)

Select all <i> elements inside <p> elements:

$('p i')

Child Selector : ">"

Select all <ul> elements that are immediate children of a <li> element:

$('li > ul')

Adjacent Sibling Selector : "+"

Select all <a> elements that are placed immediately after <h2> elements:

$('h2 + a')

General Sibling Selector : "~"

Select all <span> elements that are siblings of <div> elements:

$('div ~ span')

$('.a .b , .a .c').css('border', '2px solid yellow');
//selects b and c
<script src=""></script>

<div class="a">a
  <div class="b">b</div>
  <div class="c">c</div>
  <div class="d">d</div>


Vanilla JavaScript solution:-



Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]