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?
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();
.
$("li a.link").click(function(e) {
var i = $(this).parent().index();
alert(i);
});
If you want to get the physical number (e.g. first returns one, second returns two), you'd just add one to the selector:
$("li a.link").click(function(e) {
var i = $(this).parent().index() + 1;
alert(i);
});
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):
var li_elems = $('li.link'),
i = 0,
len = li_elems.length;
for (; i < len; i++) {
li_elems[i].attr('index', i);
}
$('ul').on('click', 'li.link', function (e) {
var index = this.getAttribute('index');
alert(index);
});