Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finding index of element

Tags:

jquery

I have some HTML like this:

<div class="TopClass">

  <div class="ContentClass">
    <div class="ActionClass">action</div>
  </div> 

  <div class="ContentClass">
    <div class="ActionClass">action</div>
  </div> 

  <div class="ContentClass">
    <div class="ActionClass">action</div>
  </div> 

</div>

I'm looking to get the index of the action class relative to TopClass; if the user clicks on the second Action class, it should return 2.

$('.ActionClass').click(function () {
    alert($(this).parent().parent().index());  // not working    
});
like image 800
frenchie Avatar asked Nov 29 '25 02:11

frenchie


1 Answers

Use .index like this which will always give you the index of .ActionClass even if the structure changes. But as .index returns 0-based index I am adding 1 into it's output:

$('.ActionClass').click(function () {
   alert($(this).closest('.TopClass').find('.ActionClass').index(this) + 1);
});​

Working Fiddle

Another shorter way can be like this, it works fine with only one parent .TopClass container so far but use carefully if you have a different structure. Previous one is safer and works for general cases

$('.ActionClass').click(function () {
   alert($('.ActionClass').index(this) + 1);
});​

Working Fiddle

like image 183
Prasenjit Kumar Nag Avatar answered Nov 30 '25 14:11

Prasenjit Kumar Nag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!