views:

795

answers:

1

I want to count the div that has a class name "items" and has an attribute "style=display:none".

<div id="skills">
<div class="items" style="display:none">1</div>
<div class="items">2</div>
<div class="items">3</div>
<div class="items" style="display:none">4</div>
<div class="items" style="display:none">5</div></div>

the output should be '3'.

===========================================================

addition to the problem:

<div id="skills1">
<div class="items" style="display:none">1</div>
<div class="items">2</div>
<div class="items">3</div>
<div class="items" style="display:none">4</div>
<div class="items" style="display:none">5</div></div>

<div id="skills2">
<div class="items" style="display:none">1</div>
<div class="items" style="display:none">2</div>
<div class="items" style="display:none">3</div>
<div class="items" style="display:none">4</div>
<div class="items" style="display:none">5</div></div>

the output shoub be '3' & '5'.

+7  A: 

Original:

var count = $('div.items:hidden').length;

New:

var counts = {};
$('#skills1,#skills2').each( function() {
    counts[$(this).attr('id')] =  $('div.items:hidden', $(this)).length;
}

The counts object will be:

{ skills1 : 3, skills2 : 5 }

Last(?)

$('#skills1,#skills2').each( function() {
    if ($('div.items:hidden',$(this)).length == 0) {
        $(this).hide();
    }
});

It would be even easier if you gave the "containers" a class to use as a selector. Then you could simply replace #skills1,#skills2 with the class selector and not have the function be dependent on the names of the DIVs, meaning that it wouldn't have to change if you add another container, say skills3. You'd just have to make sure to give that container the correct class.

tvanfosson
thanks tvanfosson!..but i have a little bit complicated problem. how will i do this dynamically? pls. see the additional problem..thanks again in advance..
scoohh
in your answer: var count = $('div.items:hidden').length;if 'count' is equal to 0 and its parent id is 'skills1' then the div with the id 'skills1' will then display 'none'..
scoohh
@scoohh -- you want to hide the DIV when the number of hidden elements contained in it is 0 or when the number of hidden items is equal to the number of items? Your last comment has me confused.
tvanfosson
i want to hide the DIV when the number of hidden items is equal to 0..
scoohh
@scoohh -- I've added a solution for that as well. As you're new, you'll want to remember to vote up helpful answers and accept the best answer (providing it's correct) by clicking the check mark next to the votes.
tvanfosson
it works fine!..thanks a lot to you tvanfosson..
scoohh
and thanks for the advice..=))
scoohh