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.
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.
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 .
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.
you can use
$('li a.editEntity').live('click', function() { $(this).parents('li').addClass('selected'); }); 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.