Sachin Jain
Sachin Jain

Reputation: 21842

Access elements having multiple classes using jQuery

Sometimes we have defined some elements with multiple classes like :-

<div class="a b c"> Hi this is div with multiple classes </div>

Now, I want to access this div using jQuery selectors So I was trying :-

var cls = "a b c"; 
$("." + cls); // Returns []

Makes sense because it is actually trying to find all the elements with classname as "a" and then trying to find the children "b" and "c" further inside the element with class "a" which is wrong semantically. So i found a way around to find such elements which is :-

var a = "mk-search-contents boundary-top";
var all = $("div"); // Assuming I know the tagname if element i am interested in

for (var i=0; i<all.length; i++) {
    if (all.get(i).className == a) { console.log(all.get(i)); break; }
}

And it gave me correct answer but I failed to understand, why this is working and how to select such elements using jQuery.

Upvotes: 3

Views: 1567

Answers (2)

Murali Murugesan
Murali Murugesan

Reputation: 22619

Try the below selector to match all three classes

$('.a.b.c')

If you want to match any of three

$('.a,.b,.c')

Upvotes: 0

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382464

Simply use this selector :

$('.a.b.c')

className gives you all the classes names separated by spaces ("a b c"). But for css and jquery selectors you can't use "a b c".

What you did was

$('.a b c')

which means "the c elements in b elements in elements of class a".

Upvotes: 5

Related Questions