Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 397
Tomkay Avatar asked Dec 22 '25 10:12

Tomkay


1 Answers

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()

like image 81
Bill Avatar answered Dec 24 '25 00:12

Bill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!