Siddharth Thevaril
Siddharth Thevaril

Reputation: 3788

Get index of an element using index() in jQuery

$(document).ready( function() {
  var box = $('.box');
  box.click( function() {
    console.log($(this).index());
  });
});
div, section {
  border: 1px solid red;
  width: 80px;
  height: 80px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">1</div>
<div class="box">2</div>
<div class="para">3</div>
<div class="box">4</div>

In the above HTML, the last div with class .box is the 3rd .box and I want the index of the last .box to be 3, but I get 4. Which jQuery function should I used instead which will search all divs with class box and then return me the position of .box in the set on clicking the .box?

Upvotes: 0

Views: 35

Answers (1)

j08691
j08691

Reputation: 207861

You can use .index() when you compare it to a set of elements with $('.box').index($(this))

If a selector string is passed as an argument, .index() returns an integer indicating the position of the first element within the jQuery object relative to the elements matched by the selector.

BTW, .index() is zero-based so the indices would be 0, 1, and 2. If you want 1, 2, and 3, just add 1 to the result.

$(document).ready(function() {
  var box = $('.box');
  box.click(function() {
    console.log($('.box').index($(this)));
  });
});
div,
section {
  border: 1px solid red;
  width: 80px;
  height: 80px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">1</div>
<div class="box">2</div>
<div class="para">3</div>
<div class="box">4</div>

Upvotes: 3

Related Questions