Find item position in list

I am looking to find the position (i.e. order) of a clicked item in a list using jQuery.

I have:

<ul> <li>Element 1</li> <li>Element 2</li> <li>Element 3</li> ... </ul> 

When I click <li> I want to save it in a variable. For example, if I clicked on element 3, then "3" would be stored in a variable.

How can this be achieved?

Many thanks for your help!

+8
jquery
Jan 12 '10 at 2:30
source share
3 answers

Use index() :

 $("li").click(function() { var index = $(this).parent().children().index(this); alert("You clicked item " + index); }); 

Indexes start at 0.

+29
Jan 12 '10 at 2:32
source share

The previous answer is working fine. 2 additions:
When your list contains a list of <a> elements, for example:

 <ul id="test"> <li><a href="#">Element 1</a></li> <hr /><hr /> <li><a href="#">Element 2</a></li> <li><a href="#">Element 3</a></li> </ul> 

then you should use var index = $(this).parent().parent().children().index(this);

As in the previous example, the list contains other elements, such as <hr /> , than you can use the filter in var index = $(this).parent().parent().children("li").index(this); to give you index 2 for "element 3" instead of index 4.

0
10 May '15 at 21:20
source share

A more efficient version of Cletus answer that does not require searching for parents and children:

 $("li").on("click", function() { var index = $(this).index(); alert(index); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li>Element 1</li> <li>Element 2</li> <li>Element 3</li> <li>Element 4</li> </ul> 
0
May 22 '17 at 1:28
source share



All Articles