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

What is the best way to get 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 on the c element, is there a best practice for getting an index from 2 from an event handler?

I know that I can determine the position of an element by looking at its parent, but I do not know if there is a better or more concise way.

+5
source share
3 answers
+9
source

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

So you can write:

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

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

+7
source

.

$(this).prevAll("li").size();

vie Felix.

0

All Articles