cusejuice cusejuice - 2 months ago 8
jQuery Question

jQuery: Get number of elements that have a certain class

How do I get the number of elements that have the particular class

.added
when the element with the class
.header
is clicked?

<ul class="main">
<li class="header">Header</li>
<li class="added">One</li>
<li>Two</li>
<li class="added">Three</li>
<li>Four</li>
</ul>


So in this case, when I click the element with the class
.header
I would want to retrieve the number 2.

Answer

length should work. size() is deprecated as of jQuery 1.8.

Example:

$('.header').on('click', function () { 
    return $('.added').length;
});

See: http://api.jquery.com/length/