Finding the index of a list item in jQuery

Posted by Tim Piele on Stack Overflow See other posts from Stack Overflow or by Tim Piele
Published on 2012-06-06T22:02:53Z Indexed on 2012/06/06 22:40 UTC
Read the original article Hit count: 204

Filed under:
|
|

I have an unordered list of eight items. On page load the first five <li> have default thumbnail images in them and the 6th one has a 1px by 1px placeholder image with the ID of $('#last'). When a user inserts a new image it replaces the 'src' of $('#last') with their new image. It's not the most efficient way but it works.

<ul>
    <li><img src="img1.png" /></li>
    <li><img src="img2.png" /></li>
    <li><img src="img3.png" /></li>
    <li><img src="img4.png" /></li>
    <li><img src="img5.png" /></li>
    <li><img src="1px.png" id="last"/></li>
    <li></li>
    <li></li>
</ul>

When the user adds a new image the ID of $('#last') is removed and I use each() to find the next empty <li> and insert the 1px by 1px image in it, with an ID of $('#last') so it is ready for the next image upload.

At this point I need to get the index() of the <li> that now has the 1px by 1px image in it, whose ID is $('#last'), so that I can store the index in the session, so when a user comes back to the page the $('#last') ID is still set and ready to accept another image.

How do I get the index of the <li> with that image in it, since it was set after page load? Is there a way to use delegate() or on() to get it? i.e. how do I get the index of an element that was set after page load?

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about list