Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 433
Daniel W. Avatar asked Oct 15 '13 12:10

Daniel W.


People also ask

How do you check the div is visible or not in jQuery?

How to Check an Element is Visible or not using jQuery. You can use .is(':visible') to check whether an element is visible in the layout or not. Elements are considered visible if they consume space in the document.

How do I count the number of divs inside a div?

To count all elements inside a div elements, we use find() method and length property. The find() method is used to find all the descendant elements of the selected element.

How do I count the number of elements in jQuery?

Answer: Use the jQuery . length property You can simply use the jQuery . length property to find the number of elements in a DIV element or any other element. The following example will alert the number of paragraphs in a <div> element having the class . content on document ready event.

Is visible condition in jQuery?

You can use the jQuery :visible selector to check whether an element is visible in the layout or not. This selector will also select the elements with visibility: hidden; or opacity: 0; , because they preserve space in the layout even they are not visible to the eye.


1 Answers

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;
like image 107
James Donnelly Avatar answered Sep 29 '22 10:09

James Donnelly