Is there a way to count how many elements on the page with a particular class?
7 Answers
$('.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.
-
1Am not locating it, but I read on Meta recently "How do you upvote?", and there was a Jeff Atwood quote "Whenever I research for an issue and find the Answer." My exact situation. Sep 11, 2013 at 22:59
-
17
-
1
-
1@TylerLazenby: You sure about that? jsfiddle.net/xpvt214o/154885 Do you have an example to demonstrate your claim?– DavidApr 18, 2018 at 19:30
-
2@TylerLazenby: The code in your question isn't using jQuery. You're just getting the length of a string literal.– DavidApr 18, 2018 at 19:35
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:
$('.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.
use the .size()
method or .length
attribute