0

$(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?

2
  • The index being returned is taking into consideration all the elements within the parent. If you want to filter you can either provide a selector for the method or call it against a selector. jQuery .index() Commented Dec 15, 2016 at 20:43
  • api.jquery.com/index it's well documented. Commented Dec 15, 2016 at 20:44

1 Answer 1

3

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.