Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 960
Mladen Avatar asked Jun 24 '09 22:06

Mladen


People also ask

How do you find an element with multiple classes?

Use the getElementsByClassName method to get elements by multiple class names, e.g. document. getElementsByClassName('box green') . The method returns an array-like object containing all the elements that have all of the given class names.

Can we use two classes in jQuery?

The . class selector can also be used to select multiple classes. Note: Seperate each class with a comma. Note: Do not start a class attribute with a number.

Can we use multiple selectors in jQuery?

You can specify any number of selectors to combine into a single result. This multiple expression combinator is an efficient way to select disparate elements. The order of the DOM elements in the returned jQuery object may not be identical, as they will be in document order.


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

like image 113
Sasha Chedygov Avatar answered Oct 13 '22 00:10

Sasha Chedygov