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

Log the nth-child number

How do I log the the nth-child number of an element in a container using jQuery. Thanks in advance.

$('.wrapper p').on('click', function() {
  //log the nth-child number of the clicked element
  console.log($(this).nth-child())
})
p {
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="wrapper">
  <p>first</p>
  <p>second</p>
  <p>third</p>
</div>

Example: Say you pressed the <p> tag with content second then the log would be 2 because the <p> tag is found in the second position of the container.

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

>Solution :

You can use Array.from to convert NodeList to Array of Elements and use indexOf to get index of child

$('.wrapper p').on('click', function() {
  const allElements = $('.wrapper p');
  const index = Array.from(allElements).indexOf(this) + 1
  console.log(index)
})
p {
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="wrapper">
  <p>first</p>
  <p>second</p>
  <p>third</p>
</div>
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