...
...
...
I have several di...">

Count visible divs using jQuery

HTML:

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

I have several divs with categories as a class (and more divs without .male inside them), when I start, I count them

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

(I know that size(); deprecated, but we are using an older version of jQuery)

During application, some of the divs become invisible after a certain click. I want to list the visible elements.

I tried

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

But that gave me a terrible big number, like 3050, so I suppose the selector really counts all visible .male inside .male or something like that.

Can someone give me the correct selector only for visible divs with a specific class?

+7
javascript jquery html jquery-selectors
source share
2 answers

You need to remove the space between .male and :visible , otherwise you target all visible elements in .male :

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

Here's a demo of JSFiddle showing both.

UPDATE: jQuery 1.8 abandoned its size() method in favor of using the JavaScript length property. Now we can:

 $('.male:visible').length; 
+19
source share

Remove the space from your selector:

 $('.male:visible').size(); 
+8
source share

All Articles