143

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

7 Answers 7

285
$('.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.

9
  • 1
    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.
    – brasofilo
    Sep 11, 2013 at 22:59
  • 17
    Notice that .size() method is Deprecated. Jan 22, 2014 at 17:37
  • 1
    with version 3.1.1, length returns undefined Nov 26, 2016 at 12:53
  • 1
    @TylerLazenby: You sure about that? jsfiddle.net/xpvt214o/154885 Do you have an example to demonstrate your claim?
    – David
    Apr 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.
    – David
    Apr 18, 2018 at 19:35
28
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/

9

I believe this works:

$(".MyClass").length 
0
7

try this:

var count_element = $('.element').length
6
$('.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.

3

The best way would be to use .each()

var num = 0;

$('.className').each(function(){
    num++;
});
1
  • 2
    "The .each() method is designed to make DOM looping constructs concise and less error-prone"
    – Panomosh
    Jan 26, 2017 at 12:25
2

use the .size() method or .length attribute

1

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.