Jquery: Which child element did I click?

I need to return a numeric value of which child element was clicked using jQuery. I have something like this…

<div id="mylist">
    <img src="image1.jpg"/>
    <img src="image2.jpg"/>
    <img src="image3.jpg"/>
    <img src="image4.jpg"/>
    <img src="image5.jpg"/>

If I click on image1, I want it to return 0. If click image3, return 2, etc.

I know I can get the number of children by using $(‘#mylist’).children.length, but I’m not sure how to combine the use of .parent() to achieve this.

Bump please :slight_smile:

No expert on jQuery, but since nobody else has answered… I assume if you somehow attached an onclick handler to all those children generically, you have a pointer to the clicked object with “this” in that function. So loop over this.parent().children from 0 to this.parent().children.length-1, and compare this.src to that child’s src.

jQuery has an ‘index’ function for this very purpose:

$('#mylist img').bind('click', function(){
    alert( $('#mylist img').index(this) );

Perfect, thank you! This is the final code I used (a bit shorter)

$('#mylist img').click(function(){
    alert( $('#mylist img').index(this) );