Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the position of an element within a list

Tags:

jquery

I'm looking to find the position (i.e. the order) of a clicked element within a list using jQuery.

I have:

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

On click of an <li>, I want to store it's position within a variable. For example, if I clicked on Element 3, then "3" would be stored in a variable.

How could this be achieved?

Thanks much for your help!

like image 626
Simon Avatar asked Jan 12 '10 02:01

Simon


1 Answers

Use index():

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

Indexes start at 0.

like image 196
cletus Avatar answered Oct 23 '22 00:10

cletus