Daniel W.
Daniel W.

Reputation: 32280

Count visible divs with jQuery

HTML:

<div class="male">...</div>
<div class="male">...</div>
<div class="female">...</div>

I have several divs with categories as class (and more divs without .male inside of them), on startup I count them with

$('.male').size(); // Returns 40 items for example

(I know size(); is deprecated but we use an older version of jQuery)

During the application, some of the divs turn invisible after a specific click, I want to recount the visible items.

I tried

$('.male :visible').size();

But it gave me a horrible high number, like 3050, so I assume the selector does count all the visible divs inside .male or something.

Is someone able to advice me the correct selector for only visible divs with specific class?

Upvotes: 18

Views: 24290

Answers (2)

James Donnelly
James Donnelly

Reputation: 128791

You need to remove the space between .male and :visible, otherwise you're targeting all visible elements within .male:

$('.male:visible').size();

Here's a quick JSFiddle demo showing both.

UPDATE: jQuery 1.8 deprecated its size() method in favour of using JavaScript's length property instead. We can now:

$('.male:visible').length;

Upvotes: 43

tymeJV
tymeJV

Reputation: 104775

Remove the space from your selector:

$('.male:visible').size();

Upvotes: 8

Related Questions