Get index of clicked element in collection using jQuery

How to get the index of the clicked item in the code below?

$('selector').click(function (event) { // get index in collection of the clicked item ... }); 

With Firebug, I saw this: jQuery151017197709735298827: 2 (I clicked on the second item).

+48
javascript jquery events jquery-selectors
Apr 04 2018-11-11T00:
source share
5 answers

This will warn the index of the selected selector (starting at 0 for the first):

 $('selector').click(function(){ alert( $('selector').index(this) ); }); 
+82
Apr 04 '11 at 23:16
source share
 $('selector').click(function (event) { alert($(this).index()); }); 

jsfiddle

+52
Apr 04 '11 at 23:17
source share

Brothers and sisters

$(this).index() can be used to get the index of the clicked item if the items are siblings.

 <div id="container"> <a href="#" class="link">1</a> <a href="#" class="link">2</a> <a href="#" class="link">3</a> <a href="#" class="link">4</a> </div> 

 $('#container').on('click', 'a', function() { console.log($(this).index()); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <div id="container"> <a href="#" class="link">1</a> <a href="#" class="link">2</a> <a href="#" class="link">3</a> <a href="#" class="link">4</a> </div> 



Not brothers and sisters

If the argument is not passed to the .index() method, the return value is an integer indicating the position of the first element in the jQuery relative to its twin elements .

Pass the selector to index(selector) .

 $(this).index(selector); 

Example:

Find the index of the <a> element that is clicked.

 <tr> <td><a href="#" class="adwa">0001</a></td> </tr> <tr> <td><a href="#" class="adwa">0002</a></td> </tr> <tr> <td><a href="#" class="adwa">0003</a></td> </tr> <tr> <td><a href="#" class="adwa">0004</a></td> </tr> 

violin

 $('#table').on('click', '.adwa', function() { console.log($(this).index(".adwa")); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <table id="table"> <thead> <tr> <th>vendor id</th> </tr> </thead> <tbody> <tr> <td><a href="#" class="adwa">0001</a></td> </tr> <tr> <td><a href="#" class="adwa">0002</a></td> </tr> <tr> <td><a href="#" class="adwa">0003</a></td> </tr> <tr> <td><a href="#" class="adwa">0004</a></td> </tr> </tbody> </table> 
+16
Mar 22 '16 at 10:06
source share

Just do this: -

 $('ul li').on('click', function(e) { alert($(this).index()); }); 

OR

 $('ul li').click(function() { alert($(this).index()); }); 
+10
Apr 26 '12 at 11:05
source share

if you use .bind (this) try the following:

let index = Array.from(evt.target.parentElement.children).indexOf(evt.target);

 $(this.pagination).find("a").on('click', function(evt) { let index = Array.from(evt.target.parentElement.children).indexOf(evt.target); this.goTo(index); }.bind(this)) 
0
Oct 08 '18 at 14:00
source share



All Articles