0

I have the following code:

var $thumbs = $('.thumbs');

$thumbs.on('click', 'a', function($e) {
  $e.preventDefault();
  var $this = $(this);

  console.log($this.parent().index('.thumbs'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="col xs4 s12 m4 push-m8 thumbs">
   <div class="col xs4 s6">
       <a href=""><img src="img_url.jpg"></a>
       <a href=""><img src="img_url.jpg"></a>
       <a href=""><img src="img_url.jpg"></a>
       <a href=""><img src="img_url.jpg"></a>
    </div>
  
    <div class="col xs4 s6">
        <a href=""><img src="img_url.jpg"></a>
        <a href=""><img src="img_url.jpg"></a>
        <a href=""><img src="img_url.jpg"></a>
     </div>
</div>

<div class="col xs4 s12 m4 push-m8 thumbs">
     <div class="col xs4 s6">
        <a href=""><img src="img_url.jpg"></a>
        <a href=""><img src="img_url.jpg"></a>
        <a href=""><img src="img_url.jpg"></a>
        <a href=""><img src="img_url.jpg"></a>
      </div>
      <div class="col xs4 s6">
         <a href=""><img src="img_url.jpg"></a>
         <a href=""><img src="img_url.jpg"></a>
         <a href=""><img src="img_url.jpg"></a>
       </div>
</div>

All I want to know is what is the index of thumbs when a a element is clicked. So when a is clicked from the first thumbs I would expect the return to be 0 and from the second thumbs to be 1. However for some reason I'm only getting -1 returned.

Here are some more jQuery examples I've already tried () but without success:

Community
  • 1
  • 1
SuperDJ
  • 7,488
  • 11
  • 40
  • 74

1 Answers1

2

The problem is that the .thumbs element is not the parent of the a element that was clicked. You need to traverse up the tree of elements.

You could do this with .parent().parent(), but that isn't very robust. Use closest instead:

console.log($this.closest('.thumbs').index('.thumbs'));
lonesomeday
  • 233,373
  • 50
  • 316
  • 318