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.
Call $(this).index()
.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With