SanJeet Singh
SanJeet Singh

Reputation: 1331

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?

Upvotes: 0

Views: 1305

Answers (2)

n-dru
n-dru

Reputation: 9430

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.

Upvotes: 1

Christian
Christian

Reputation: 28144

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)

Upvotes: 0

Related Questions