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
});
Use
.indexlike this which will always give you the index of.ActionClasseven if the structure changes. But as.indexreturns0-basedindex I am adding1into it’s output:Working Fiddle
Another shorter way can be like this, it works fine with only one parent
.TopClasscontainer so far but use carefully if you have a different structure. Previous one is safer and works for general casesWorking Fiddle