Count elements with jQuery

Jquery

Jquery Problem Overview


Is there a way to count how many elements on the page with a particular class?

Jquery Solutions


Solution 1 - Jquery

$('.someclass').length

You could also use:

$('.someclass').size()

which is functionally equivalent, but the former is preferred. In fact, the latter is now deprecated and shouldn't be used in any new development.

Solution 2 - Jquery

var count_elements = $('.class').length;

From: http://api.jquery.com/size/

> The .size() method is functionally > equivalent to the .length property; > however, the .length property is > preferred because it does not have the > overhead of a function call.

Please see:

http://api.jquery.com/size/

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

Solution 3 - Jquery

Yes, there is.

$('.MyClass').size()

Solution 4 - Jquery

I believe this works:

$(".MyClass").length 

Solution 5 - Jquery

try this:

var count_element = $('.element').length

Solution 6 - Jquery

$('.class').length

This one does not work for me. I'd rather use this:

$('.class').children().length

I don't really know the reason why, but the second one works only for me. Somewhy, either size doesn't work.

Solution 7 - Jquery

The best way would be to use .each()

var num = 0;

$('.className').each(function(){
    num++;
});

Solution 8 - Jquery

use the .size() method or .length attribute

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsantaView Question on Stackoverflow
Solution 1 - JqueryDavidView Answer on Stackoverflow
Solution 2 - JqueryDavid HoudeView Answer on Stackoverflow
Solution 3 - Jqueryg.d.d.cView Answer on Stackoverflow
Solution 4 - JqueryIronicMuffinView Answer on Stackoverflow
Solution 5 - JqueryNaftaliView Answer on Stackoverflow
Solution 6 - JqueryKiss KoppányView Answer on Stackoverflow
Solution 7 - JqueryPanomoshView Answer on Stackoverflow
Solution 8 - JqueryneebzView Answer on Stackoverflow