So, I have a navigation that is a list and has sublists and sublists.
Basically, the nav is by default collapsed, but if people click on a page that\'s in a sublist,
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...
Try with this code line:
$(this).parent().parent().fadeOut();
This will give you the fifth:
$(this).parents(':eq(4)');
To simplify Lance McNeary's very helpful answer, the trick is to use:
.parents([selector])
Given a jQuery object that represents a set of DOM elements, the .parents() method allows us to search through the ancestors of these elements in the DOM tree and construct a new jQuery object from the matching elements ordered from immediate parent on up; the elements are returned in order from the closest parent to the outer ones.
Another user suggested:
.closest([selector])
Similar to .parents(), this may be a better choice as it stops once it finds the element it is looking for. Seems like it would be more efficient in this case. See http://api.jquery.com/closest/ for more details. Hope this helps people understand the differences between .closest() and .parents() and how powerful and flexible jQuery can be.
$(this).parents().get()[4]
will give you the fifth