Moving up multiple parents in jQuery - more efficient way?

If I understand what you're trying to do... you can do something like this:

// For my benefit, hide all lists except the root items
$('ul, li', $('#lesson-sidebar ul li')).hide();

// Show active parents and their siblings
$('li a.active').parents('ul, li').each(function() {
    $(this).siblings().andSelf().show();
});

// Show the active item and its siblings
$('li a.active').siblings().andSelf().show();

The parents() and siblings() methods are both great for this kind of thing.

Edit: There was a bug before where it wasn't showing parent siblings. Try this new version.

Edit 2: Now it works with class="active" on the anchor instead of the list item.


$(this).closest("ul") will traverse the parents until it finds a ul

http://docs.jquery.com/Traversing/closest#expr

...get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree...