Home Ask Login Register

Developers Planet

Your answer is one click away!

SanJeet Singh February 2016

How to get index of clicked link in jQuery?

This is my markup:

<div>
<h2><a href="link-here">Link Text</a></h2>
<p>Description</p>
<h2><a href="link-here">Link Text</a></h2>
<p>Description</p>
<h2><a href="link-here">Link Text</a></h2>
<p>Description</p>
.. Unknown number of such elements...
</div>

When a user clicks a link I wanted to get its index. I tried to use $(this).index(); but it returns zero. How can I get the link?

Answers


Christian February 2016

The reason for your issue is that index() will return a result relative to the parent of this, which is always the h2 element. In other words, index() will always be zero for your case.

However, if you read the documentation, you'll find that index() also has some variants, such as the 2nd option where you can specify how to retrieve the index from a list of items via a selector.

Here's an example: https://jsfiddle.net/d7rpuv6d/ (please open the console to see the result)


n-dru February 2016

This will work:

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

in jQuery documentation (https://api.jquery.com/index/) we read:

If .index() is called on a collection of elements and a DOM element or jQuery object is passed in, .index() returns an integer indicating the position of the passed element relative to the original collection.

Post Status

Asked in February 2016
Viewed 2,240 times
Voted 5
Answered 2 times

Search




Leave an answer


Quote of the day: live life