frenchie
frenchie

Reputation: 52027

finding index of element

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    
});

Upvotes: 3

Views: 88

Answers (4)

Josh Koberstein
Josh Koberstein

Reputation: 176

$index = jQuery.inArray($(this)[0], $('.ActionClass')) + 1

This solution will work regardless of the HTML structure. It finds the array index of the clicked '.ActionClass' element in the array containing all matched '.ActionClass' elements.

Upvotes: 1

Prasenjit Kumar Nag
Prasenjit Kumar Nag

Reputation: 13461

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

Upvotes: 6

amelvin
amelvin

Reputation: 9061

Your parent().parent() is taking you too high in the structure:

$('.ActionClass').click(function () {
    alert($(this).parent().index());  // not working    
});​

Will work, but its zero based so you'll get 0, 1 and 2 for the three div clicks.

http://jsfiddle.net/amelvin/AhReg/

EDIT

Based on you amendment you can use the optional selector variable on the index() method.

<div class="TopClass">

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

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

  <div class="test"></div>
  <div class="test"></div>  
  <div class="test"></div>
  <div class="test"></div>  
  <div class="test"></div>
  <div class="test"></div>  

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

</div>​

$('.ActionClass').click(function () {
    alert($(this).parent().index(".ContentClass"));  // not working    
});​

Upvotes: 1

Ja͢ck
Ja͢ck

Reputation: 173652

Your code is almost correct, just get index from parent node:

$('.ActionClass').click(function () {
    alert($(this).parent().index());
});

Disclaimer

This doesn't work when there are other siblings besides .ContentClass. For that you should refer to Joy's answer.

Upvotes: 2

Related Questions