3

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.

1
  • Hey dystroy..I am extremely sorry about that. I didn't see the timings and did not read the comments. I just tried the answer and ticked the one which was showing on top..BTW corrected it. Commented Oct 3, 2012 at 12:07

2 Answers 2

5

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".

Sign up to request clarification or add additional context in comments.

Comments

0

Try the below selector to match all three classes

$('.a.b.c')

If you want to match any of three

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

3 Comments

No : this would match elements having any of the three classes, not all the three classes.
For all three classes $('.a.b.c');
timestamps are a wondrous thing :P

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.