I have a class of multiple ‘DIV’ elements and inside it are list of ‘p’ elements. See below:
<div class="container">
<p>This is content 1</p>
<p>This is content 2</p>
<p>This is content 3</p>
</div>
<div class="container">
<p>This is content 1</p>
<p>This is content 2</p>
<p>This is content 3</p>
</div>
Here’s my jQuery code on calling the ‘p’ elements through hover:
$('.container').children('p').hover(function(){
//get the nth child of p from parent class 'container'
});
How can I get the nth child number of the element ‘p’ from its parent container class ‘container’?
Like if you hover
This is content 1
it should trigger output as 1;
You can use jQuery’s
indexfunction for that. It tells you where the given element is relative to its siblings:Live example | source
The indexes are 0-based, so if you’re looking for a 1-based index (e.g., where the first one is
1rather than0), just add one to it:If you’re not using jQuery and came across this question and answer (the OP was using jQuery), this is also quite simple to do without it.
nth-childonly considers elements, so: