Find the position of an element within a list
jquery
Solution
A more efficient version of Cletus' answer, which doesn't require finding parents and children:
$("li").on("click", function() {
var index = $(this).index();
alert(index);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>Element 1</li>
<li>Element 2</li>
<li>Element 3</li>
<li>Element 4</li>
</ul>
Problem
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!