flyingL123
flyingL123

Reputation: 8076

How to use JQuery index() method

What am I missing regarding JQuery's index() method. Based on the documentation, I would expect to be alerted a value of 1 here:

HTML

<div class="test" id="div1"></div>
<div class="test" id="div2"></div>

JS

$(document).ready(function(){
    var index = $('.test').index('#div2');
    alert(index);
});

Here's a fiddle: http://jsfiddle.net/cpody1cb/

Why am I alerted -1? If I instead use index('#div1'), I am alerted 0, as I would expect.

Upvotes: 2

Views: 788

Answers (3)

Kevin B
Kevin B

Reputation: 95022

.index() can only work on one element, so it starts by reducing the set of selected elements to only the first one, which explains why you get 0 when you use #div1 and -1 when you use #div2. You should be selecting the div you want the index of, and then giving it a selector to tell it where to look for the element.

$('#div2').index('.test')

Upvotes: 0

isherwood
isherwood

Reputation: 61063

You're trying too hard.

var index = $('#div2').index();

To explain why yours doesn't work, you simply have the selectors backward. The argument for the index() method should be a selector that gets the set of elements, not the element for which you want the index. This would be done like so:

var index = $('#div2').index('.test');

Upvotes: 2

PeterKA
PeterKA

Reputation: 24638

Since the indexes are zero-based you should get 1

$(document).ready(function(){
    var index = $('.test').index( $('#div2') );
    alert(index);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="test" id="div1"></div>
<div class="test" id="div2"></div>

Upvotes: 0

Related Questions