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

11,621

Solution 1

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.

Solution 2

If you have no other anchors inside the navbar,

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

If you have nested anchors, as are common in navbars, this will do:

$('#navbar>li>a').click( function () {
    var curpos = $('#navbar>li>a').index(this);
});

Solution 3

In your code, you're trying to access ul.navbar but the ul has no class named navbar. To access it by ID, use the ID selector #

Also, you just need to use index() which gets the index of the current element in relation to it's siblings. Use the .parent() to get the li and then access the index of that.

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

Example: http://jsfiddle.net/jonathon/SyvZ5/

Solution 4

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

should do the trick.

Share:
11,621
benpalmer
Author by

benpalmer

Updated on June 04, 2022

Comments

  • benpalmer
    benpalmer almost 2 years

    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