Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get index of click element by class

I have some HTML like this:

<div class="slide">
  <a href="#" class="test">Test</a>
</div>
<div class="other">
  ...
</div>
<div class="slide">
  <a href="#" class="test">Test</a>
</div>
<div class="other">
  ...
</div>

Now, when I click on one of the test links, I want to get the index of the parent div. BUT, I want the indexes to be just of the div.slide elements.

I've tried the following:

$('a.test').click(function(){
  var slideIndex = $(this).parents('.slide').index();
  alert(slideIndex);
});

The above alerts 0 for the first link and 2 for the second link. I want it to alert 1 for the second link as it's the second div.slide. How can I change what I've done to do this?

like image 560
CaribouCode Avatar asked Sep 26 '13 14:09

CaribouCode


1 Answers

Pass the selector to index(), or use the selector and pass the element -> $('.slide').index($(this).closest('.slide')), either way works :

$('a.test').click(function(){
  var slideIndex = $(this).closest('.slide').index('.slide');
  alert(slideIndex);
});
like image 91
adeneo Avatar answered Nov 05 '22 15:11

adeneo