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!
Use index()
:
$("li").click(function() {
var index = $(this).parent().children().index(this);
alert("You clicked item " + index);
});
Indexes start at 0.
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