Reputation: 2126
I need to count hidden elements regardless of parent visibility.
I have this code:
<div id="parent-1">
<div class="item" style="display: none;"></div>
<div class="item" style="display: none;"></div>
<div class="item"></div>
<div class="item" style="display: none;"></div>
</div>
<script>
var hidden_items = $('#parent-1').find('.item:hidden').length;
console.log (hidden_items);
</script>
In this example I get 3 items, so is correct.
But with this code:
<div id="parent-2" style="display: none;">
<div class="item" style="display: none;">
<div class="item" style="display: none;">
<div class="item">
<div class="item" style="display: none;">
</div>
<script>
var hidden_items = $('#parent-2').find('.item:hidden').length;
console.log (hidden_items);
</script>
I get 4 elements! because parent is a hidden element, but I need to get 3.
Any ideas?
Upvotes: 1
Views: 1022
Reputation: 67207
That is because, When a parent element is hidden the children elements of it will also be hidden. That is the natural behavior. If you still want to get the elements regardless of its parent display property then use .filter
with its callBack
function.
var hidden_items = $('#parent-2 .item').filter(function(){
return this.style.display == "none"
}).length;
Upvotes: 1
Reputation: 82241
You can use filter function to filter out elements that have display property set as none:
var hidden_items = $('#parent-2 .item').filter(function(){
return $(this).css('display') == "none"
}).length;
Working Snippet:
$(function(){
var hidden_items = $('#parent-2 .item').filter(function(){
return $(this).css('display') == "none"
}).length;
alert (hidden_items);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent-2" style="display: none;">
<div class="item" style="display: none;">
<div class="item" style="display: none;">
<div class="item">
<div class="item" style="display: none;">
</div>
Upvotes: 1