开发者

jQuery count div that has a display:none attribute

开发者 https://www.devze.com 2022-12-20 23:05 出处:网络
I want to count the div that has a class name \"items\" and has an attribute \"style=display:none\". <div id=\"skills\">

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>

<开发者_C百科;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 should be '3' & '5'.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号