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.
Simply use this selector :
classNamegives 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
which means “the c elements in b elements in elements of class a”.