Tomkay
Tomkay

Reputation: 5160

Get parent's index() value of the child

How do I get the parent element's index value in relation to the document, of the clicked child, $(this), element?

HTML

<html>
   <body>
      <header>
         <div class="gallery">
            <div class="controls">
               <button class="next"></button>
               <button class="previous"></button>
            </div>
         </div>
      </header>
      <section>
         <section>
            <article>
               <div class="gallery">
                  <div class="controls">
                     <button class="next"></button>
                     <button class="previous"></button>
                  </div>
               </div>
               <div class="gallery">
                  <div class="controls">
                     <button class="next"></button>
                     <button class="previous"></button>
                  </div>
               </div>
            </article>
         </section>
      </section>
   </body>
</html>

In this HTML it is possible to declare a gallery at any place you like within the body. So I need an “intelligent” selector to solve the problem.

Pseudo JavaScript

$('.controls button').click(function() {
   var hope = $(this).parents('.gallery').index();
   alert(hope);
}

Expected output

Scenario
Click on a button of the second gallery in this document:

1

Upvotes: 3

Views: 982

Answers (2)

Bill
Bill

Reputation: 3517

Try this:

$('.gallery').index( $(this).parents('.gallery') );

.index() is finding the index of the passed element in the group of elements that it is applied to.

Take a look at my working jsFiddle example.

source(s)

jQuery API - .index()

Upvotes: 5

Brian Stephens
Brian Stephens

Reputation: 5271

When you call index(), it gives you the position relative to the collection of elements you have selected, in this case,

$(this).parents('.gallery')

Instead, you want it relative to the galleries in the entire document, so you need:

$('.gallery').index($(this).parents('.gallery'))

Upvotes: 4

Related Questions