vimuth
vimuth

Reputation: 5612

Get visible and not hidden items with jquery

I need a to take all li elements to array. And ul and li both should be not visibility: hidden and not display: none. This is my code.

var links = $("li").is(":visible").is(":hidden");
var currentLink = links.first();

alert(currentLink.text());

This is my list

<ul>
   <li style='display: none'>Coffee</li>
   <li style='visibility: hidden'>Tea</li>
   <li>Milk</li>
</ul> 

(I need to show tea in alert and not coffee)

but I'm getting this error,

TypeError: $(...).is(...).is is not a function

Upvotes: 0

Views: 73

Answers (2)

vimuth
vimuth

Reputation: 5612

By looking at the answers I manage to create a perfect answer. I'm posting it in case if someone in the future may came up with same issue. Thanks so much for everyone helped me.

var links = [];
$("li:not(:hidden)").each(function(index, item){
    if($(item).css("visibility") != "hidden"){
       links.push(item); 
    }
});

Upvotes: 0

Hien Nguyen
Hien Nguyen

Reputation: 18975

You can use .css("visibility") != "hidden"

$(document).ready(function(){
    $('ul li').each(function(index, item){
        if($(item).css("visibility") != "hidden"){
          console.log($(item).text())
        }
    })
})

$(document).ready(function(){
    $('ul li').each(function(index, item){
        if($(item).css("visibility") != "hidden"){
          console.log($(item).text())
        }
    })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li>Test visible</li>
<li style="visibility: hidden">Hidden</li>
<li>Test visible2</li>
</ul>

Upvotes: 1

Related Questions