BD_Design BD_Design - 8 months ago 48
jQuery Question

jQuery - Count list children not containing div with class

I have a simple js script that counts the number of children an unordered list has. I'm trying to change the script so it doesn't count any children (li) which contain a div with the class 'hiddenItem'. Here's the list and the js.

<ul id="dlist" class="sortable">
<li id="listItem_000002">
<div><a class="itemCollapse"></a>
</div>Item 2</div>
<li id="listItem_000003">
<div><a class="itemCollapse"></a>
</div>Item 3</div>
<li id="listItem_000009">
<div><a class="itemCollapse"></a>
</div>Item 9</div>
<li id="listItem_000012">
<div class="hiddenItem">
<div><a class="itemCollapse"></a>
</div>Item 12 (Hidden)</div>

<a class="count">Count</a>


$(".count").click(function () {
var tcount = $("#dlist").children("li").length;

In this example the js alerts that there are 4 items. But, I'm trying to change the code so it alerts 3 items, due to the last list item containing the div with the class 'hiddenItem.' I've tried to use .filter() as well as a few other transverseing methods with no luck. Anyone have a better idea?

Here's a working fiddle:

Any help would be appreciated. Thanks!

Answer Source

You can use not method.

var tcount = $("#dlist > li").not(':has(div.hiddenItem)').length;

Or filter method:

var tcount = $("#dlist > li").filter(function(){
                 return $('div.hiddenItem', this).length === 0;