frenchie
frenchie

Reputation: 51927

finding index of parent of a certain class

I have the following HTML:

<div class="Wrapper">

   <div class="SomeOtherClass"></div>
   <div class="SomeOtherClass"></div>

   <div class="MyClass">
       <div class="SomeElement" id="test"></div>
       <div class="SomeElement"></div>
   </div>

   <div class="MyClass">
       <div class="SomeElement" id="test2"></div>
       <div class="SomeElement"></div>
   </div>   

</div>

And I have the following javascript:

$('.Wrapper').find('.SomeElement').each(function () {

    if (SomeCondition) {

       var TheElement = $(this);
       var TheIndexOfParentClass = TheElement... //HERE

       return;
    }
});

As you can see, I loop through all the SomeElements and I pick one. Now I want to know the index of the parent's class (here "MyClass"). For instance, if I pick out "test" then the TheIndexOfParentClass should be 0 and if I pick out test2 then TheIndexOfParentClass should be 1. Note that the number of elements of SomeOtherClass can vary; I don't want the actual index of the parent, I want the index of the parent's class relative to all children of the Wrapper element. How do I do this?

Thanks.

Upvotes: 1

Views: 126

Answers (2)

user2538908
user2538908

Reputation:

If you want to stick with your flow, You could do this also by passing class to index method,

$('.Wrapper').find('.SomeElement').each(function () {

 if (SomeCondition) {

  var TheElement = $(this);
  var TheIndexOfParentClass = TheElement.parent().index('.MyClass'); //HERE
       return;
 }
});

What we are avoiding here is double each loop.

Upvotes: 0

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382092

I think you want this :

$('.Wrapper').find('.MyClass').each(function(TheIndexOfParentClass) {
    $('.SomeElement', this).each(function(){
       if (SomeCondition) {
          var TheElement = $(this);

each pass to the callback the iteration index and so by decomposing the iteration you can ask jQuery to count for you.

Upvotes: 3

Related Questions