Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count li elements that are visible with jQuery

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!

like image 358
Dominic Avatar asked Apr 13 '12 06:04

Dominic


3 Answers

work fine for me

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

JsFiddle Lind : http://jsfiddle.net/xuckF/1/

like image 51
Rony SP Avatar answered Nov 02 '22 02:11

Rony SP


Works fine here:

http://jsfiddle.net/jtbowden/FrPPr/ (1 visible)

http://jsfiddle.net/jtbowden/FrPPr/1/ (0 visible)

Now, using numbers as class names is illegal. (W3C Spec, bullet 2) Class names must start with a letter. Maybe doing manipulations with that is causing problems?

Other than that, I can only guess your problem is elsewhere. Are you using the latest version of jQuery? (Although in my tests, it works all the way back to 1.3, and then it doesn't work at all)

Did you misspell "visible" in your actual code. (I've done this before)

like image 8
Jeff B Avatar answered Nov 02 '22 02:11

Jeff B


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/

like image 2
Matija Grcic Avatar answered Nov 02 '22 04:11

Matija Grcic