Edit
  • How to find the 2nd closest ancestor in jQuery?

    My DOM looks something like this:

    <li> <li><a class="editEntity>Edit</a></li> <li><a class="deleteEntity>Delete</a></li> </li> 

    When the user clicks on "Change", I want to change the external <li> to <li class="selected> .

    I tried something like this, but this does not work:

     $('li a.editEntity').live('click', function() { $(this).closest('li').closest('li').addClass('selected'); }); 

    Any help is appreciated.

    +9
    source share
    3 answers

    Raise the parent:

     $(this).closest('li').parent().closest('li').addClass('selected'); 

    It did not work because closest starts with the current element, so if you call it on what matches the selector, you are returning the same thing that you started with.

    Living example

    Or you can use parents with a selector :eq :

     $(this).parents("li:eq(1)").toggleClass("selected"); 

    Note that :eq uses 0-based indexes, therefore :eq(1) is the second parent of li .

    Real time example

    Your quoted HTML is not valid though ( li cannot contain li directly ); I assume you meant:

     <li> <ul> <li><a class="editEntity>Edit</a></li> <li><a class="deleteEntity>Delete</a></li> </ul> </li> 

    ... or similar.

    +19
    source

    you can use

     $('li a.editEntity').live('click', function() { $(this).parents('li').addClass('selected'); }); 
    +1
    source

    after my previous comment .. here the example promised ... :)

     $('li').each(function(index) { alert(index + ': ' + $(this).text()); }); 

    Stop at the second index

    Further information can be found here.

    http://api.jquery.com/each/

    0
    source

    All Articles