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. So, Only the Elements That Have Both Classes. When I Use $(". A, .B") It Gives Me the...
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.
14 Answers
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').)
You can do this using the filter() function:
$(".a").filter(".b")
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')
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!
Must Read
Group Selector : ","
Select all <h1> elements AND all <p> elements AND all <a> elements :
$('h1, p, a')