Count li elements that are visible with jQuery

2020-06-03 01:41发布

Im counting my li elements with the following jQuery script:

HTML:

<ul class="relatedelements">
   <li style="display:none;" class="1">anything</li>
   <li style="display:none;" class="2">anything</li>
   <li style="display:none;" class="3">anything</li>
</ul>

jQuery:

    $(function() {
        var numrelated=$('.relatedelements > li').length;
        $('.num-relatedelements').html(numrelated); 
    });

--> The script returns: 3

I change the style="display: none" property of some of the li elements when $(document).ready with jQuery, like: $('.2').show();

I now want to change the script in a way to count only the visible li elements with the following script (i just added :visible following the jQuery docs):

    $(function() {
        var numrelated=$('.relatedelements > li:visible').length;
        $('.num-relatedelements').html(numrelated); 
    });

--> The script returns: nothing

I have no clue why it doesn't work out - maybe anyone has any tip or idea? Any help is much appreaciated. Thanks upfront!

9条回答
beautiful°
2楼-- · 2020-06-03 02:34

Element assumed as hidden if it or its parents consumes no space in document. CSS visibility isn't taken into account.

View:

<ul class="relatedelements">
   <li class="1 hidden">anything</li>
   <li class="2 hidden">anything</li>
   <li class="3 hidden">anything</li>
   <li class="4">anything</li>
    <li class="5">anything</li>
    <li class="6">anything</li>
    <li class="7 hidden">anything</li>
</ul>

<div class="num-relatedelements"></div>

CSS

.hidden {
    display: none;
}​

JS

$(function() {  
   var numrelated= $('.relatedelements > li:not(.hidden)').length;
   alert(numrelated);
   $('.num-relatedelements').html(numrelated); 
});​

I've made a jsfiddle for you: http://jsfiddle.net/mgrcic/3BzKT/3/

查看更多
Ridiculous、
3楼-- · 2020-06-03 02:40

Just take a look at this: http://jsfiddle.net/vnMrQ/

查看更多
何必那么认真
4楼-- · 2020-06-03 02:45

In line one simply define a div or span or paragraph where you want to display count, and in second line the ul containing li

 $('.notify').html(
 $('#ul-notifications li').length);
查看更多
登录 后发表回答