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()
.size() is now removed as of jQuery 3.0.
9 Comments
brasofilo
Am 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.
Moshe Simantov
Notice that
.size() method is Deprecated.Giovanni Bitliner
with version 3.1.1, length returns undefined
David
@TylerLazenby: You sure about that? jsfiddle.net/xpvt214o/154885 Do you have an example to demonstrate your claim?
David
@TylerLazenby: The code in your question isn't using jQuery. You're just getting the length of a string literal.
|
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:
Comments
$('.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.
1 Comment
GuiRitter
Same for me. I was testing in a React web app I had developed. I didn't install jQuery, so it must be available from one of the dependencies. I was searching for
$("tr") and I suspect that, in some cases, it returns the first element instead of all of the matched ones.use the .size() method or .length attribute
1 Comment
Amine ABBAOUI
.size() is deprecated