-1

I'm trying to detect wether there is .product which css is display: block; (visible) in .calendar-paper or not.

var $objArr = $('.calendar-paper');
$objArr.each(function(i) {
    var $thisCalendar = $objArr.eq(i);
    if(!$thisCalendar.find('.product').filter(':visible')) {
        // Do something if the content of .calnedar-paper is empty 
    } else {
       
    }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="calendar-paper">
    <div class="product" style="display: block;">...</div>
    <div class="product" style="display: none;">...</div>
</div>

<div class="calendar-paper">
    <div class="product" style="display: block;">...</div>
</div>

And the result shows that even if the .product css display: none, still run the else condition. That's not what I expect. Please explain to me where the logic goes wrong. Thank you.

hayley
  • 384
  • 5
  • 17

1 Answers1

1

You're missing to find it's length:

if($thisCalendar.find('.product').filter(':visible').length) {

But I suspect that you wanted to use :empty selector instead of :visible selector.

if($thisCalendar.find('.product:empty').length) {
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
  • This is because just like @str said `filter()` always returns a jQuery object and I will always get true in the if-else condition. So I need to test the length of the object right? – hayley Aug 15 '20 at 11:37