Find child index using jQuery?

If I have an html structure, for example:

<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 class second ( first, second, third classes are just added to make a demo cleaner) there an easy way to get number 1, since this is the second child? (Index based on 0)?

Something like $(this).index

+4
source share
2 answers

Just take a look at the jQuery API. The method you suggest, index , is correct:

 $('#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 jQuery relative to its sibling elements.

Also note that I slightly changed the selector from your example. I assume it was just a typo in your question. #parent.child will look for the element with the identifier "parent" and the class "child", but you really want #parent .child (note the space) to search for elements with the class "child" that are descendants of the element with the identifier "parent" .

+10
source

The index() method can be used to get the position of an element within a collection. In basic circumstances, $(this).index() should work.

But with more specific collections, you can get the position using collection.index(item) . Imagine you are adding something simple to your #parent , which should not be taken into account when measuring index() (a span , img , whatever). With a simple method, your code is likely to break, but with a specific method it will not.

Something like this should work for you:

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

jsFiddle Demo

+2
source

Source: https://habr.com/ru/post/1410833/


All Articles