147

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

7 Answers 7

294
$('.someclass').length

You could also use:

$('.someclass').size()

.size() is now removed as of jQuery 3.0.

Sign up to request clarification or add additional context in comments.

9 Comments

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.
Notice that .size() method is Deprecated.
with version 3.1.1, length returns undefined
@TylerLazenby: You sure about that? jsfiddle.net/xpvt214o/154885 Do you have an example to demonstrate your claim?
@TylerLazenby: The code in your question isn't using jQuery. You're just getting the length of a string literal.
|
29
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/

Comments

9

I believe this works:

$(".MyClass").length 

Comments

7

try this:

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

Comments

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

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.
3

The best way would be to use .each()

var num = 0;

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

1 Comment

"The .each() method is designed to make DOM looping constructs concise and less error-prone"
1

use the .size() method or .length attribute

1 Comment

.size() is deprecated

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.