Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Where is the position of the child element? – jquery

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading