jQuery – get index of Selected element

jQuery provides index() method to find out index of any element. This method return value is an integer indicating position of the element.
$(document).ready(function(){
   $('table tr').mouseover(function(){
       $(this).css("cursor","pointer");
   });
   $('table tr').click(function(){
       var index = $('table tr').index(this);
       alert('You Clicked row ' + index);
    });
});
HTML:
<table>
<tr>
<td>Row 1</td>
</tr>
<tr>
<td>Row 2</td>
</tr>
<tr>
<td>Row 3</td>
</tr></table>
 – OR – 
jQuery-
$("div").click(function () {
  var index = $("div").index(this);
  $("span").text("That was div index #" + index);
});

HTML:

 

<span>Click a div!</span>
<div>First div</div>
<div>Second div</div>
<div>Third div</div>


Live Demo 

 

Share this nice post:

One thought on “jQuery – get index of Selected element

Leave a Reply

Your email address will not be published. Required fields are marked *