how can i get child element position in JQuery?
I want to get the number 2 in the alert, because it is the second child!
function where_am_i(element) {
alert("your position is:" + $(element).position_element());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li>one</li>
<li onclick="where_am_i(this)">two</li>
<li>three</li>
</ul>
>Solution :
Use jQuery’s .index() method. Note that it returns a zero-based index so you’ll need to add one to get the value you want.
$("ul li").on("click", function() {
alert(`your position is: ${$(this).index() + 1}`)
})
li { margin: 1rem auto; cursor: pointer; }
li:hover { text-decoration: underline; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.slim.min.js"></script>
<ul>
<li>one</li>
<li>two</li>
<li>three</li>
</ul>