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?
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.
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.
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With