Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you extract the nth-child value in JQuery?

Tags:

jquery

I have a list of an indeterminate number of child elements:

<ul>
    <li ID="alpha"></li>
    <li ID="bravo"></li>
    ...
    <li ID="hotel"></li>
    ...
</ul>

If I were to click on any of these elements, would it be possible to find out which child number they are in the list, and pass that value to a variable?

like image 460
DLaugharn Avatar asked Feb 26 '11 05:02

DLaugharn


2 Answers

Yes, the jQuery index method will give you that info:

$(this).index(); // will return the index relative to its other siblings.

http://api.jquery.com/index/

like image 94
Eli Avatar answered Oct 02 '22 18:10

Eli


As of 1.4,

$('li').click(function(){
   alert( $(this).index() );
});
like image 44
Stefan Kendall Avatar answered Oct 02 '22 16:10

Stefan Kendall