I am trying to figure out how to get the number of nth child of a selected element. For example if I have:
<parent>
<child>a</child>
<child>b</child>
<child>c</child>
<child>d</child>
<child>e</child>
</parent>
Then if I have:
$('child').click(function(){
console.log($(this).nthChildOf('parent'));
});
And I like the console to output 3
if I click on c
.
Thanks for the speedy answer. I have an added question. I find that if I use:
<parent>
<child onclick="nthOf(this)">a</child>
<child onclick="nthOf(this)">b</child>
<child onclick="nthOf(this)">c</child>
<child onclick="nthOf(this)">d</child>
<child onclick="nthOf(this)">e</child>
</parent>
and then:
function nthOf(e) {
console.log($('parent').index(e));
}
It will always output 1.
And if I do:
function nthOf(e) {
console.log($('parent').index($(e)));
}
It will always output -1.
How do I fix this?