AnonyMouse
AnonyMouse

Reputation: 18630

jquery how to get the first list item with display:none

Ok, so I have this div which contains a ul:

    <html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" ></script>
<script type="text/javascript">
$(document).ready(function(){
  $("button").click(function(){
    alert($('#slider ul li[display="none"]:first').text());
  });
});
</script>
<style type="text/css">
li
{
display:inline;
margin: 20px;
}
</style>
</head>
<body>
<div id="slider" style="width:100%; overflow-x:hidden"><ul><li style="display:none">Steve 1</li><li style="display:none">Frank</li><li>Tim</li><li>Steve</li><li>Frank</li><li>Tim</li><li>Steve</li><li>Frank</li><li>Tim</li><li>Steve</li><li>Frank</li><li>Tim</li><li>Steve</li><li>Frank</li><li>Tim</li><li>Steve</li><li>Frank</li><li>Tim</li><ul>
</div>
<button type="button" style="float:left">Previous</button><div style="float:right">Next</div>
</body>
</html>

What I wanted to happen is that when you press the Previous button it would find the first item in the list with display none and show a message with it's content. In this case Steve1.

So I used $('#slider ul li[display="none"]:first') which means it should find the div named slider and it's first list item in the ul with display:none.

I get a blank back in the message.

Anyone know what I'm doing wrong.

I think it's got to do with the attribute part which I constructed from:

http://api.jquery.com/attribute-equals-selector/

Upvotes: 1

Views: 9515

Answers (2)

Andreas Wong
Andreas Wong

Reputation: 60516

$('#slider ul li:hidden:first') is what you are looking for

http://api.jquery.com/hidden-selector/

:hidden matches the following conditions, according to the link above

Elements can be considered hidden for several reasons:

  1. They have a CSS display value of none.
  2. They are form elements with type="hidden".
  3. Their width and height are explicitly set to 0.
  4. An ancestor element is hidden, so the element is not shown on the page.

Upvotes: 10

Jasper
Jasper

Reputation: 76003

$('#slider ul li[style="display:none"]:first')

Square brackets select elements based on attributes. There was no display attribute. But the style attribute can be used. If the style attribute has other styles than just display:none then you can use a RegExp selector:

$('#slider ul li[style*="display:none"]:first')

The asterik (*) means that the string can exist anywhere inside the actual value of the attribute.

Here is a demo: http://jsfiddle.net/TAv3d/

Docs for jQuery selectors: http://api.jquery.com/category/selectors/

Alternatively you can use functions for DOM traversal (and it's a bit faster):

$('#slider').children('ul').children('li').filter('[style="display:none"]').first();

Upvotes: 2

Related Questions