Search code examples
jqueryjquery-selectorscss-selectorsparent-childparent

How do I get the index of the current item in relation to the parent element with jQuery?


I am trying to get the index of the current item within

<ul id="navbar">
    <li><a href="#a">Link</a></li>
    <li><a href="#b">Link</a></li>
    <li><a href="#c">Link</a></li>
    <li><a href="#d">Link</a></li>
    <li><a href="#e">Link</a></li>
</ul>

I am using jQuery and have got the total by simply using

$('ul#navbar').children().length;

How do I get the current index in relation to the parent element?

eg. Third link is clicked, 3 is returned or 2 if as an array.

I've tried the following but keep returning -1 for not found

$('ul#navbar a').click(function(){
    var curPos = $(this).parent().parent().index($(this).parent());
});

EDIT: Changed the ul.navbar in the javascript to ul#navbar, apologies


Solution

  • Using the index() method on the parent li element

    var curPos = $(this).parent().index();
    

    http://api.jquery.com/index/

    If no argument is passed to the .index() method, the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements.