Count elements with jQuery
JqueryJquery 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:
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