DLaugharn
DLaugharn

Reputation: 51

Can you extract the nth-child value in 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?

Upvotes: 5

Views: 3207

Answers (3)

JohnP
JohnP

Reputation: 50019

Yup, you can use the .index() method. Example here : http://jsfiddle.net/jomanlk/Gy88N/

Code follows

<ul>
    <li ID="alpha">Item 1</li>
    <li ID="bravo">Item 2</li>
    <li ID="hotel">Item 3</li>
    <li ID="hotel2">Item 4</li>
    <li ID="hotel3">Item 5</li>
</ul>


$('ul li').click(function(e){
    alert($(this).index())
})

Upvotes: 2

Stefan Kendall
Stefan Kendall

Reputation: 67832

As of 1.4,

$('li').click(function(){
   alert( $(this).index() );
});

Upvotes: 2

Eli
Eli

Reputation: 17825

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/

Upvotes: 17

Related Questions