Reputation: 3
I've been reading lots of posts that do similar things using addClass(), parent(), closest(), filter(), how CSS doesn't have a parent selector, etc., and I'm getting nowhere fast so I truly appreciate your help. :-)
I have an unordered list that is generated by a CMS, so I can't add or change any of the classes in it. I can only touch the CSS and I can use jQuery.
When the user selects a list item, the CMS adds a class of "selected" to it, and also to that li's parent li, grandparent li, and so on up the tree depending on how far down in the menu the selected item is.
I can only use this one unordered list for both the main nav and a side nav that gets displayed on the left side of interior pages.
In the sidenav I need to display only the ul that has a selected li in it, including all of the li's in that parent ul not just the selected ones. For example, if my menu has two sections, About Us and Giving, and someone selects a page from the About Us section, I want to display only the About Us li's not the Giving ones. (Later I'll add styling to the top-level li and the li of the page that the user selected.)
I understand how to display the li's that have a class of selected but I need to show all li's if the ul has a selected li anywhere in it. Also, I need to not display any other ul's in the list if those ul's don't have selected li's in them.
Here's my HTML. In this example, the user has gone to the Policies page under About Us->Our Commitment.
<ul class="main-menu sm sm-simple">
<li class="menuItem1 first parent selected"><a href="#">About Us</a>
<ul class="nccUlMenuSub1">
<li class="menuItem1 first parent selected"><a href="#">Our commitment</a>
<ul class="nccUlMenuSub2">
<li class="menuItem1 first"><a href="#">Operating standards</a></li>
<li class="menuItem2 selected last"><a class="selected" href="#">Policies</a></li>
</ul>
</li>
<li class="menuItem2 last"><a href="#">Annual Report</a></li>
</ul>
</li>
<li class="menuItem2 last parent"><a href="#">Giving</a>
<ul class="nccUlMenuSub1">
<li class="menuItem1 first last"><a href="#">What your gift can do</a></li>
</ul>
</li>
</ul>
Upvotes: 0
Views: 1742
Reputation: 104
This may be more what you are looking for.
$('li.selected').find('.selected').show(); //get all grandchilden
$('li.selected').find('.selected').siblings().show(); // get all sibling except root
find ignores the root node so 'About Us' sibling 'Giving will not be shown. Additionally, based on your markup, you have a child tag that need to be identified as well.
Upvotes: 0
Reputation: 38253
This should work:
$('li.selected').show();
$('li.selected').siblings('li:not(.parent)').show();
It will display all of the list items that are siblings of a selected one.
Also, you have some malformed HTML, so I'm wondering if it is a typo or the CMS is actually outputting invalid HTML:
<li class="menuItem2 last parent"><a href="#">Giving</a> <!-- This -->
<ul class="nccUlMenuSub1">
Upvotes: 1