I was reading a lot of questions here about getting value of index.
I know how to get li
on click index number. However, I need to get the li
value when the link within it is clicked.
<ul>
<li><a class=link href="#"></a></li>
<li><a class=link href="#"></a></li>
<li><a class=link href="#"></a></li>
<li><a class=link href="#"></a></li>
</ul>
$("li a.link").click(function(e) {
var i = $(this).index();
alert(i)
});
It won't work because it takes the index of a.link
not ul li
. How can I get index of the li
when a specific a.link
is clicked?
There are two approaches you can take: count which position the clicked li is, or number them beforehand. The second is much more efficient (constant time on a click):
You can use jQuery's parent() selector to target the index of the parent element of the clicked anchor link.
In this case, it would be:
$(this).parent().index();
.If you want to get the physical number (e.g. first returns one, second returns two), you'd just add one to the selector: