Reputation: 399
In the following line of code, a call to the index() function for the first element in a set returns 1. Why does it not return 0?
var firstBlockIndex = $( '.block' ).first().index();
Upvotes: 1
Views: 1105
Reputation: 23660
Consider the HTML block below:
<div>
<span></span>
<span class="block"></span>
<span class="block"></span>
</div>
Then
$('.block').first().index();
returns 1 because
If no argument is passed to the .index() method, the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements.
Within the <div>
block there are 4 <span>
tags. The first()
one with class "block" is the second tag. Thus it's index is 1 as index()
is zero-based (ref).
Demo: JSFiddle
To get the position of an element relative to all matched elements, you can pass in a selector or element to index()
to get the index of some narrowed-down selector within the set. Consider this HTML block:
<div>
<span></span>
<span class="block"></span>
<span class="block"></span>
<span class="block special"></span>
</div>
Then
$('.block').index( $(".special") ));
will return 2 because the span with class "special" is the 3rd element in the group of elements of class "block".
Demo: JSFiddle
Upvotes: 5
Reputation: 17550
index()
returns the index of an element relative to its siblings, not relative to the other selected elements (see the documentation).
Added code snippet to show the behavior:
$(function() {
$('#result').text($('li.block').first().index());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="firstList">
<li class="noblock">First item</li>
<li class="block">Second item</li>
<li class="noblock">Third item</li>
</ul>
<ul id="secondList">
<li class="noblock">First item</li>
<li class="block">Second item</li>
<li class="noblock">Third item</li>
</ul>
Index of first li.block element:
<span id="result"></span>
Upvotes: 0