I am trying to figure out how to traverse into elements depending on a class name and perform some action if it has this class or do something else if it doesn’t.
Please see my code so far:
<script type="text/javascript">
jQuery(document).ready(function($) {
var container = $('.container');
container.each(function() {
// if all list item has class of hidden then hide parent container
container.hide();
// if not all list item has class of hidden then show parent container
container.show();
});
});
</script>
<div class="container container1">
<ul>
<li class="item">item 1</li>
<li class="item hidden">item 2</li>
<li class="item">item 3</li>
<li class="item">item 4</li>
</ul>
</div>
<div class="container container2">
<ul>
<li class="item hidden">item 1</li>
<li class="item hidden">item 2</li>
<li class="item hidden">item 3</li>
<li class="item hidden">item 4</li>
</ul>
</div>
From the code above the desired result is container2 should be completely hidden because all the list item within has a class of “hidden”. While container1 shows because not all list items have the class “hidden”.
As you can see, I got as far as using the “each” function to iterate through the containers but I am stuck on how to implement where it will check each list item for the specific class. My thought would be to perform another each function within it? But not sure…
Thanks for looking.
You can further select with
containeras context and hide the container, when the number of hidden items is equal to all list items. Show otherwise.See JSFiddle for testing.