bragboy
bragboy

Reputation: 35542

How to get a div with multiple classes count using jQuery

I have a sample HTML like the following,

<div class="class1"></div>
<div class="class2 class3"></div>

And my JS is,

alert(jQuery(".class1").length);
alert(jQuery(".class2 class3").length);

For the first alert I am getting 1 as expected, but I am getting 0 for the second alert. How to get the value 1 for the second alert as well. I need specifically this case (where a div has both class2 and class3). Help me.

Thanks

Upvotes: 3

Views: 4128

Answers (3)

Elnaz
Elnaz

Reputation: 2890

('.class2 class3') has no meaning.

('.class2 .class3') : an element with class3 which is a child of an element with class2 .
('.class2.class3'): an element which has class2 AND class3, both.

Upvotes: 1

Robert
Robert

Reputation: 21388

Take out the space and you're missing a dot, the selector you're looking for is $('.class2.class3')

Upvotes: 3

Quentin
Quentin

Reputation: 943216

You want '.class2.class3'

What you have ('.class2 class3') means "A <class3> element that is a descendent of an element that is a member of class2".

Upvotes: 10

Related Questions