Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: best way to get the index of an element in an event handler

Tags:

jquery

What is the best way to retrieve the index of an element in an event handler:

<ul>
  <li>a</li>
  <li>b</li>
  <li>c</li>
</ul>

$("ul li").click(function() {
  // what is the index of the list item that was clicked?
});

In other words, if I click the 'c' item, is there a best practice for getting the index of 2 from within the event handler?

I know I can determine the element's position by looking at its parent, but I don't know if there is a better or more concise way.

like image 557
tilleryj Avatar asked Mar 25 '11 19:03

tilleryj


2 Answers

Call $(this).index().

like image 190
SLaks Avatar answered Oct 26 '22 18:10

SLaks


Yes, there is an "index" method for this.

So you could write:

$("#ul_id li").click(function() {
  var index = $("#ul_id li").index(this);
});

Here's the documentation: http://api.jquery.com/index/

like image 34
Adam Albrecht Avatar answered Oct 26 '22 18:10

Adam Albrecht