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.
>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>