find index of child using jQuery?

html, javascript, jquery

Solution

Just have a look at the jQuery API. The method you suggest, `index`, is exactly right:

$('#parent .child').click(function() {
    var index = $(this).index();
});

From the docs:

If no argument is passed to the .index() method, the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements.

Also note that I've changed the selector slightly from your example. I'm guessing that was just a typo in your question though. `#parent.child` will look for an element with ID "parent" and a class of "child", but you actually want `#parent .child` (note the space) to find elements with class "child" that are descendants of an element with ID "parent".

Problem

If I have an html structure like: ``` <div id="parent"> <div class="child first"> <div class="sub-child"></div> </div> <div class="child second"> <div class="sub-child"></div> </div> <div class="child third"> <div class="sub-child"></div> </div> </div> ``` and I have a click handler defined through `($('#parent.child')).click()` and then I click on the div with the class of `second` (`first, second, third` classes have simply been added to make demo clearer) is there a simple way to get the number 1 as it is the second child? (0 based index)? Something like `$(this).index`

Original source

Related problems