Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery index of element of a certain class

Tags:

jquery

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.

like image 427
frenchie Avatar asked Jan 12 '23 22:01

frenchie


1 Answers

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.

like image 133
dsgriffin Avatar answered Jan 22 '23 02:01

dsgriffin