Nathan
Nathan

Reputation: 53

jQuery - How to find if all matching elements are display:none?

I have a list of divs similar to the simplified code below, which I've set up with a filter via a dropdown (so if you select an option in the drop down, all of the divs that don't match are set to display:none).

<div id="productlist">
   <div class="product book">Title</div>
   <div class="product book">Title</div>
   <div class="product game">Title</div>
   <div class="product movie">Title</div>
   <div class="product game">Title</div>
</div>

In the event that there are no matches however, I'd like to display a message stating as such.

Is there a way of setting an if statement, that if all divs that match the class "product" (or if all immediate children of #productlist) are set to display:none, to show the message?

Thanks

Upvotes: 2

Views: 1990

Answers (2)

Mike Mertsock
Mike Mertsock

Reputation: 12015

Using the is method makes your intent quite clear:

if (!$('.product').is(':visible')) {
  alert('No visible products found.');
}

is(':visible') returns true if any of the selected divs is visible, so the if(!$('.product').is(':visible')) statement will fire only none of the divs are visible.

Upvotes: 0

Jeff Wilbert
Jeff Wilbert

Reputation: 4520

This is achieved through the use of the :visible selector and the .length method such as so

if ($('.product:visible').length == 0)
{
    alert('No visible products found.');
}

Upvotes: 3

Related Questions