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.
3
Answers
You can use Array.from to convert NodeList to Array of Elements and use
indexOf
to get index of childYou can use JQuery
index
method too.This whole thing can be two lines (or one if you want to be creative) inside the event handler. OR leverage the jQuery index function for super simple.
First, simple example just logs index.
More complex shows some results.
Here I added some extra to handle multiple target groups, and show some results with some icky borders for clarity.
I increased the "index" for these to start from 1; but they really start from 0.
Simple, no results details:
Expanded for more details