Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the index of a list item with Jquery

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.

like image 782
Paul Sheldrake Avatar asked Oct 27 '09 19:10

Paul Sheldrake


1 Answers

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?
});
like image 162
joshperry Avatar answered Sep 26 '22 06:09

joshperry