Jitender
Jitender

Reputation: 7969

.is(':visible') does not work in jQuery

I use .is(':visible') method in jquery but it does not work as expected.

Here is my code snippet

What did I miss there?

HTML:

<div class="str">

    <ul><li>1</li><li><a href="#">hide</a></li></ul>
    <ul><li>2</li><li><a href="#">hide</a></li></ul>
    <ul><li>3</li><li><a href="#">hide</a></li></ul>
    <ul><li>4</li><li><a href="#">hide</a></li></ul>
    <ul><li>5</li><li><a href="#">hide</a></li></ul>
    <ul><li>6</li><li><a href="#">hide</a></li></ul>

    <div class="length"></div>

</div>

jQuery:

$(function(){

    $('.str ul').find('a').live('click',function(){
       $(this).closest('li').parent().hide();
       var ll= $('.str').find('ul').each(function(){  
           $('.length').text( $('.str').find('ul').is(':visible').length );  
        });   
    });

});

Upvotes: 2

Views: 4380

Answers (4)

Roko C. Buljan
Roko C. Buljan

Reputation: 206121

Use: $('.str').find('ul:visible').length

jsFiddle demo

$(function(){
    
    $('.str ul').on('click','a',function(){    
       $(this).closest('li').parent().hide();
        
       var visibleUL = $('.str').find('ul:visible').length;      
       $('.length').text( visibleUL );        
       alert(visibleUL );
        
    });
    
});

While .is() returns a boolean value ( true / false ), the :visible selector targets the desired elements creating an elements array collection - exactly what you need to return a valid array length

Upvotes: 6

adeneo
adeneo

Reputation: 318212

I would change that weird HTML to an actual list, not a bunch of lists with one item each :

<div class="str">
    <ul>
        <li>1<br><a href="#">hide</a></li>
        <li>2<br><a href="#">hide</a></li>
        <li>3<br><a href="#">hide</a></li>
        <li>4<br><a href="#">hide</a></li>
        <li>5<br><a href="#">hide</a></li>
        <li>6<br><a href="#">hide</a></li>
    </ul>
    <div class="length"></div>
</div>​

And then do:

$(function() {
    $('a', '.str ul').on('click', function() {
        $(this).closest('li').hide();
        $('.length').text($('.str ul li:visible').length);
    });
})​;​

FIDDLE

Upvotes: 1

Niko
Niko

Reputation: 26730

is(':visible') returns a boolean, not a jQuery object:

// Wrong
if ($selector.is(':visible').length) {

// Right
if ($selector.is(':visible')) {

Upvotes: 1

Quentin
Quentin

Reputation: 943579

The .is() method returns true or false

From the docs:

Unlike other filtering methods, .is() does not create a new jQuery object.

You should use find() or filter() not is().

Upvotes: 4

Related Questions