Search code examples
jqueryindexinglive

Jquery index can't find element (-1) wrong input (with live function)


I like to get the index of the li element. The li elements are created after the page loaded. Jquery returns a -1 not found error.

The structure html (found in dom, not in page source):

<div id="warp-expand">
  <ul>
   <li><div class="song"><div class="list_b"></div><a>test1</a></div></li>
   <li><div class="song"><div class="list_b"></div><a>test2</a></div></li>
  </ul>
</div>

Jquery to get the li index:

 $("#warp-expand ul li a").live('click',function () {

    var x = $("warp-expand ul li").index(this);
    alert(x); //returns -1  

 });

How the li's are made:

 $("#playlister").click(function () {
    $("#jp_playlist_2 ul li").each(function()
    {
    var s = $(this).text();
    $('#warp-expand ul').append('<li><div class="song"><div class="list_b"></div><a>' +s+ '</a></div></li>');
    });

});

Solution

  • Here you go:

    $('#warp-expand a').live('click',function () {    
        var idx = $(this).closest('li').index();    
    });
    

    Live demo: http://jsfiddle.net/Aphrq/1/

    So, as you can see, calling index() without any parameters works just fine. Just select the element (in this case the corresponding LI element) and call index() on it.


    Also, consider caching your DOM element reference on page-load:

    // cache reference on page-load (do this for all your references)
    var warp = $('#warp-expand');
    
    // use delegate(), it's better!
    warp.delegate('a', 'click', function() {
        var idx = $(this).closest('li').index();        
    });
    

    Live demo: http://jsfiddle.net/Aphrq/2/