Is there a way to show only the <ul> element that contains a specified <li> item, along with all other <li> elements within the same parent <ul>, rather than just the selected ones?

I've been browsing through various posts that deal with similar concepts like addClass(), parent(), closest(), filter(), and the limitations of CSS regarding a parent selector. Despite my efforts, I haven't made much progress, so I'd greatly appreciate your assistance. :-)

A bit of context:

I have an unordered list that is dynamically generated by a content management system (CMS), so I am unable to modify or alter any of the existing classes within it. My scope is limited to working with CSS and utilizing jQuery.

Whenever a user selects an item from the list, the CMS applies a "selected" class not only to the selected list item but also to its parent list items, grandparent list items, and so on up the hierarchy based on the depth of the selected item in the menu.

I am required to utilize this single unordered list for both the primary navigation menu and a side navigation menu displayed on interior pages.

The task at hand:

For the side navigation, I need to show only the ul element that contains a selected list item, along with all the list items in that parent ul and not just the ones marked as selected. For instance, if there are two sections in my menu - About Us and Giving - and a user selects a page from the About Us section, I should only display the list items under About Us and exclude those under Giving. (Subsequently, I will apply styling to the top-level list items and the selected page's list item.)

I know how to display list items with the selected class, but I need to reveal all list items when a ul contains a selected list item anywhere within it. Furthermore, I must hide any other ul elements in the list that do not contain selected list items.

Below is the sample HTML code where the user has navigated 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>

Answer №1

Here's a solution that should do the trick:

$('li.selected').show();
$('li.selected').siblings('li:not(.parent)').show();

This code will make all list items that are siblings of a selected one visible.

I also noticed some incorrect HTML in your code, so I'm not sure if it's a mistake or an issue with the CMS:

<li class="menuItem2 last parent"><a href="#">Giving</a>  <!-- This -->
        <ul class="nccUlMenuSub1">

Check out this Fiddle for reference.

Answer №2

Here is a potential solution that may meet your needs.

$('li.active').find('.selected').show(); //display all grandchildren
$('li.active').find('.selected').siblings().show(); // display siblings excluding parent

When using the find method, keep in mind that it does not include the parent node, so 'About Us' will not be displayed as a sibling of 'Giving.' Also, take note of the child tag within your markup that requires identification.

jsfiddle link

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Expanding the width of the containing div using CSS

I have a main container with multiple smaller divs inside it. None of these small divs have specified widths. I want the black div to expand and fill up the entire space, stretching all the way to the ABC div on the right. This only needs to work in Chr ...

Visualizing Data with d3.js Radar Charts Featuring Image Labels

After following a tutorial on creating a d3.js radar chart from http://bl.ocks.org/nbremer/21746a9668ffdf6d8242, I attempted to customize it by adding images to the labels. However, I encountered an issue with aligning the images properly. You can view my ...

It is not possible to alter or manipulate dynamic content received from an Ajax/JSON response when creating a dynamic PHP form

I am in need of a dynamic form that functions as follows: Upon clicking the "ADD" button, a new <div> element should appear for selecting a package. Based on the selected package, the row should change its color by adding or removing certain classe ...

Enhance the code for updating the content within a div element

I recently discovered that utilizing jQuery allows for updating the content within a div. My goal now is to enhance this script so the content remains consistent, even while loading or not. Take a look at my current code: function changeContent () { va ...

My current objective is to dynamically embed a pre-rendered Django template onto a specific section of my webpage through the utilization of AJAX

I came across a tutorial that demonstrates how to achieve live updates in Django without needing to refresh the entire page. The tutorial uses Flask's render_template to render the HTML and then inject it into a specific section of the page. I attempt ...

Apply a unique color to the highest value within each column using AngularJS ng-repeat

I just started learning Angularjs, and I'm not sure how to achieve this. I want to highlight the member with the highest Score, Missed, and Field Goal percentage by adding color. Is there a way to do this? https://i.sstatic.net/9KF5D.png Is it poss ...

What is the method for including footer content on a site that only has a masthead?

Is there a way to incorporate footer-type text with copyright disclaimer into a masthead-only website? I keep trying to add a footer, but it ends up getting stacked outside the masthead, causing the screen to become scrollable. My goal is to include the co ...

Trouble with ScrollTo animation on div with adjustable offset top feature - seeking assistance

Having trouble navigating to the correct slide when clicking the right button on the navigation menu. Clicking the menu button displays a list of links. Clicking on a link for the first time will take you to the correct slide, but if you try clicking a dif ...

Angular JS allows you to easily remove the # symbol from a URL, improving the

I am encountering a problem with the "#" symbol in my angular js website's URL. I need to remove the # from the URL but the method provided isn't working and the site is not displaying properly. Can someone advise me on how to successfully remove ...

Achieve text fading effects with JavaScript for a dynamic user experience in an ASP.Net C# application

In my WebForm ASP.Net application, I have implemented a feature where I change the text on the web page. To draw user attention to this change, I want to fade out the old text completely, replace it with new text, and then fade in the new text. Currently, ...

Show the image using material-ui-dropzone

Currently, I am engaged in a ReactJS project where I have implemented material-ui-dropzone to upload and exhibit an image. The uploading part has been successfully completed. However, my current obstacle lies in figuring out how to display this uploaded im ...

Tips for making POST AJAX requests to PHP/MySQL server for implementing a "favorite" button

I am seeking assistance on how to effectively send simple data via POST method to a specific page named "postData.php" in order to implement a "favorite" button. While I have the knowledge of handling POST data and forwarding it to the server, I am unsure ...

Where to place the code for HTML Email transmission

Currently, I am facing a dilemma regarding the placement of code in an email. When sending out newsletters that contain styling and images, I am unsure about where to insert the necessary code. Should I attach the images separately? Is it better to incor ...

Creating a dedicated subfolder for 4 REST API routes for better organization

I'm struggling to figure out why my .get('/:post_id') route isn't working... My project's folder structure looks like this: app.js routes --api ----blog.js The blog.js file is located in the routes/api folder. In app.js, I&apo ...

Dimension of images within bootstrap column division

I have a layout with three columns using col-md-4 for a thumbnail design, and then I have another page with col-md-8. In both cases, I need to display an image. Should I use the same image for both layouts or would it be best to have two separate images, e ...

Swiping carousel feature for mobile devices

My goal is to add carousel swipe functionality for touch devices using only JS/jQuery, without relying on any other libraries. I've created a function for this purpose: $(".carousel-inner").on("touchstart", function(event){ var xClick = event ...

SEO Friendly URL for JQuery Tabbed Content

I have developed a jQuery powered tabbed content system, where clicking on a tab changes the content below. However, I am facing an SEO issue. The SEO specialist has advised me to make it more SEO-friendly by adding different URLs to each tab. Can anyone ...

Troubleshooting a React Node.js Issue Related to API Integration

Recently, I started working on NodeJs and managed to create multiple APIs for my application. Everything was running smoothly until I encountered a strange issue - a new API that I added in the same file as the others is being called twice when accessed fr ...

What is the reason the link:visited attribute is not functioning properly for a specific page link?

I have set up links between different pages on my website. What I want is for the link that a visitor clicks on to change color once they've visited that page. Unfortunately, this feature isn't working for me and I'm not sure why. Here&apo ...

Create a grid or flex layout with Bootstrap 4 that features a sticky first row and column

Does anyone have any suggestions on how to make the attached grid/table layout responsive using Bootstrap 4's flex/grid system? The layout should include a sticky first row and column for navigation items. I attempted using w- & h- classes, but it do ...