Huangism
Huangism

Reputation: 16438

Get index of the element I clicked on relative to the jquery collection

I have a fiddle here, very simple one.

http://jsfiddle.net/tnQne/

The js I have is here

$('section a').on('click', function() {
    alert($(this).index());
});

It always returns 0 since within section there is only 1 anchor tag. What I wanted was it returns the position of the clicked element in the jquery collection. So if I clicked on the last section anchor, it would return 2 (0 based)

Upvotes: 2

Views: 156

Answers (2)

lonesomeday
lonesomeday

Reputation: 237845

You need to store the original collection and call index on that collection.

var links = $('section a').on('click', function() {
    alert(links.index(this));
});

jsFiddle


The problem with your code is that $(this).index() will get the index of the element relative to its siblings. Since the a elements don't have any siblings, the index is always 0. The API page I've linked explains how index function works if a DOM element is the argument.

Upvotes: 7

j08691
j08691

Reputation: 207901

lonesomeday has a good way to do it but another way is:

$('section a').on('click', function(e) {
    alert( $.inArray(e.target, $('section a')) );
});​

jsFiddle example

Upvotes: 2

Related Questions