I have several elements of a certain class within a container and I want to get the index of that particular element. Suppose I have this HTML:
<div id="TheContainer">
  <div class="MyClass">My Class</div>
  <div class="SomeClass">Not My Class</div>
  <div class="SomeOtherClass">Not My Class</div>
  <div class="SomeClass">Not My Class</div>
  <div class="MyClass">My Class</div>
  <div class="SomeOtherClass">Not My Class</div>
  <div class="SomeClass">Not My Class</div>
  <div class="MyClass">My Class</div>
</div>
I want to get the index of MyClass. This is what I tried:
$('#TheContainer').on({
    click: function () { 
       console.log($(this).parent().children('.MyClass').index()); }
}, '.MyClass');
So for instance, if the user clicks on the third MyClass element, it should console 2. The jsFiddle is here.
Thanks.
Note that index() has an optional element argument:
.index( element )element
Type: Element or jQuery The DOM element or first element within the jQuery object to look for.
So in this case, you could just use this as that argument:
$(this).parent().children('.MyClass').index(this);
JSFiddle here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With