2

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?

James Wayne
  • 1,894
  • 14
  • 14

1 Answers1

3

You can use .index() to get the number of element among its siblings.

$('child').click(function(){
  console.log($('child').index( this ) + 1);
});

DEMO

In reply to your recent comment, I dunno what you are trying to achieve, but if thats what you want i'll give it to you :D so as per your update to the question. Your function should be ...

function nthOf(e) {
  console.log($(e).parent().children().index(e) + 1);
}

DEMO

Mohd Abdul Mujib
  • 13,071
  • 8
  • 64
  • 88