chendriksen
chendriksen

Reputation: 1024

Get index number of jQuery element clicked

If I write a simple selector like

$('.button')

When it's clicked, can I figure out the 'index' of that button? i.e. is it the first occurrence of .button, second, third?

I know I could select the third button with $('.button')[2] but I can't figure out how to get that 2 value.

The buttons are spread across the page, rather than being all within the same div.

Upvotes: 0

Views: 1078

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

You can call the index() method to do this:

$('.button').click(function() {
  var index = $(this).index();
  console.log(index);
});

The above will give you the index of the element amongst its siblings. If you want to get the index of the element within a set, for example if the .button elements are spread around the page and not siblings, then you can provide a selector to index() to match the current element within:

$('.button').click(function() {
  var index = $(this).index('.button');
  console.log(index);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent"><button class="button">click me!</button></div>
<div class="parent"><button class="button">click me!</button></div>
<div class="parent"><button class="button">click me!</button></div>
<div class="parent"><button class="button">click me!</button></div>
<div class="parent"><button class="button">click me!</button></div>

Upvotes: 3

Related Questions