jQuery count number of divs with a certain class?

57

Considering something like this;

<div class="wrapper">
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
</div>

How would I, using jQuery (or plain JS, if it's shorter - but I doubt it) count the number of divs with the "item" class? In this example, the function should return 5, as there are 5 divs with the item class.

Thanks!

This question is tagged with jquery html count

~ Asked on 2011-09-13 15:33:33

The Best Answer is


131

You can use the jquery .length property

var numItems = $('.item').length;

~ Answered on 2011-09-13 15:34:58


19

For better performance you should use:

var numItems = $('div.item').length;

Since it will only look for the div elements in DOM and will be quick.

Suggestion: using size() instead of length property means one extra step in the processing since SIZE() uses length property in the function definition and returns the result.

~ Answered on 2011-09-13 15:38:06


Most Viewed Questions: