views:

353

answers:

2

I'm trying to find out the index number of the last list item but the jquery I'm using keeps returning -1. This is the JS and the html that I'm using.

var index = $('#imageThumbnails li:last').index(this);

<div id="imageThumbnails">
   <ul class="gallery_demo_unstyled">
      <li class="active"><img src="test-img.jpg" width="394" height="394" alt=" " /></li>
      <li><img src="test-img2.jpg" width="394" height="394" alt=" " /></li>
      <li><img src="test-img3.jpg" width="394" height="394" alt=" " /></li>
      <li><img src="test-img4.jpg" width="394" height="394" alt=" " /></li>
      <li><img src="test-img5.jpg" width="394" height="394" alt=" " /></li>
      <li><img src="test-img6.jpg" width="394" height="394" alt=" " /></li>
      <li><img src="test-img7.jpg" width="394" height="394" alt=" " /></li>
    </ul>
 </div>

Thanks for your help.

+2  A: 

You need to call index on the collection, passing in a sub-item of that collection.

var items = $('#imageThumbnails li');
var lastItem = $('#imageThumbnails li:last');
var index = items.index(lastItem);

If you are in a click function handler you could do something like this:

var items = $('#imageThumbnails li').click(function() {
    var index = items.index(this);

    // now that I know where I am, why am I here?
});
joshperry
Thanks for your help!
Paul Sheldrake
how would that second one work?
TStamper
The `items` variable is included in the interior function's closure and will be available at the time the click function executes. Since that time will be in the future the whole expression will have been completed and `items` will have been set to the array of values that resulted from the expression.
joshperry
@joshperry- yea I understand that part but the way you have it would you store the clicked index in the value, also can you click a list tag?
TStamper
Sure, you can register a click event on almost any DOM element. Unordered lists are commonly used for menus and navigation bars, the list conveys the semantics of those constructs well.
joshperry
@joshperry-you're right you can, but as I said the way you have it set up just stores the index clicked on and not the last? did you meant to do that?
TStamper
@TStamper-You are correct, the second example does not show how to get the index of the last element, it only shows how to get the index of the `li` that was clicked on. It was merely a corollary example.
joshperry
A: 

Can we impose a class with this index?

Navdeep