0

Does a child node know which child it is?

Can jQuery determine this? I'm using the nth-child and nth-of-type CSS selector heavily on this project. I suspect using this would help.

For instance, how would a function event handler look where:

upon user click on the 5th child image of a div -> alert(5).

zigo
  • 159
  • 1
  • 10

2 Answers2

3

You can use the jQuery index() function to find an element's position within a set of elements. Something like this:

$('div img').click(function() {
    var idx = $(this).closest('div').find('img').index(this);
    alert(idx);
});

This is similar to using .index() without any parameters, but it's more general-purpose, as it looks at the selected set, rather than just the immediate siblings - which may not be images.

jcsanyi
  • 8,133
  • 2
  • 29
  • 52
0
alert($(this).parent().find("img").index($(this)));

...should do it. It's zero-based.

Gary Dean
  • 21
  • 6