I have two nested ul which contain links.
I want to find the index of the clicked a within it’s parent ul
<div id="main_nav">
<ul>
<li>
<ul>
<li><a href="/url/">LINK</link></li>
<li><a href="/url/">LINK</link></li>
<li><a href="/url/">LINK</link></li>
</ul>
</li>
</ul>
<ul>
<li>
<ul>
<li><a href="/url/">LINK</link></li>
<li><a href="/url/">LINK</link></li>
<li><a href="/url/">LINK</link></li>
</ul>
</li>
</ul>
</div>
I’m using the following code:
$("#main_nav ul ul a").click(function () {
var index = $('#main_nav ul ul a').index(this);
alert(index);
});
which seems to return the index of the a within the parent of the parent instead of just the parent (I hope that makes sense) i.e. Clicking the second link in the second ul returns an index of 4 instead of 1.
Could somebody explain where I’m going wrong with this? I suspect it’s something simple but I can’t figure it out.
Many thanks.
You need to get the index of the parent
lielement. Otherwise you are getting the index of the anchor inside the list item, which will always be zero.