Reputation: 1717
I'm by no means a jQuery (or JavaScript) expert so forgive me if I'm misunderstanding or overlooking something. I have the following HTML:
<html>
<body>
<div class="ted">Ted</div>
<div class="ted">Ted</div>
<div class="tim">Tim</div>
<div class="ted">Ted</div>
<div class="tim">Tim</div>
</body>
</html>
And the following JS:
$('.ted').click(function() {
alert($(this).index());
});
When I click a div with the class '.ted'
the alert should show the index of that div
.
Clicking the first div alerts '0' (expected), the second div alerts '1' (expected). However, clicking the last '.ted'
div
(the fourth in the list) alerts '3' - why is this not giving an index of 2? (as JS arrays are 0 based) and this is the third '.ted'
div
?
It's as if $('.ted')
is actually bringing back all the divs in the list?
Example here: http://jsfiddle.net/nha2f/6/
Upvotes: 0
Views: 65
Reputation: 8606
the index is the child within the parent. If you want to enumerate the .ted
elements try this:
$('.ted').each( function( i, a ){
$(a).click( function(){
alert( i ); // <- should be 0, 1 or 2.
} );
} );
Upvotes: 0
Reputation: 1074258
To get the behavior you want, add a selector to your index
call: Fiddle
$('.ted').click(function() {
alert($(this).index(".ted"));
});
When you pass a selector into index
, it tells jQuery to look for the element in that set. If you don't, it looks to see where it is relative to all of its sibling elements.
Or alternately, remember the list of ted elements and then invert things: Fiddle
var teds = $(".ted");
teds.click(function() {
alert(teds.index(this));
});
When you pass an element into index
, that tells jQuery to look for that element in the set.
Upvotes: 0
Reputation: 72857
.index()
returns the index of the clicked element in it's parent, relative to it's siblings. Not compared to other div
s with the same event listeners / class / id. Your third '.ted'
div
is the fourth child of your body
.
Upvotes: 0
Reputation: 165971
The .index()
method docs make this behaviour clear. Here's the relevant part (emphasis added):
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.
Since the third element that matches your selector is actually the fourth child of its parent, it has an index of 3.
Continue reading through the documentation to find the solution to your problem:
If a selector string is passed as an argument,
.index()
returns an integer indicating the position of the original element relative to the elements matched by the selector.
So, you can pass the same selector to .index()
and it will return the index of the element relative to the matched set:
alert($(this).index(".ted"));
Upvotes: 3