Create a class for the grandparent element

Is there a way to dynamically add a class to a dropdown menu item when a specific child element is clicked? Here's the HTML structure I have:

<ul id="FirstLevel">
    <li><a href="#">FirstLevel</a></li>
    <li><a href="#">FirstLevel</a>
        <ul class="secondLevel">
            <li><a href="#">SecondLevel</a></li>
                   <ul class="LastLevel">
                         <li><a href="#">LastLevel</a></li>
                         <li><a href="#">LastLevel</a></li>
                   </ul>
            <li><a href="#">SecondLevel</a></li>
            <li><a href="#">SecondLevel</a></li>

        </ul>
    </li>
    <li><a href="#">FirstLevel</a></li>
    <li><a href="#">FirstLevel</a></li>
    <li><a href="#">FirstLevel</a></li>
</ul

I am looking for a solution where, on clicking a child element with the class LastLevel or SecondLevel, a class should be added to the parent li element with the class FirstLevel. The previously selected menu state should also be removed in this process.

I attempted to achieve this functionality using jQuery, but it doesn't seem to work as expected. Here's what I tried:

$('#firstUl').find('li').click(function(){ //removing the previous selected menu state $('#firstUl').find('li').removeClass('active'); //is this element from the second level menu? if($(this).closest('ul').hasClass('lastLevel')){ $(this).parents('li').parents('li').addClass('menuActive'); //this is a parent element }else{ $(this).addClass('menuActive'); } }); 

Your insights and suggestions would be greatly appreciated. Thank you.

Answer №1

Consider adding a specific class to your FirstLevel list items for easier targeting:

<li class="first-level"><a href="#">FirstLevel</a></li>

Then, you can add a click function to all child list items within the FirstLevel list items:

$('li.first-level li').on('click', function(e) {
  e.preventDefault(); // prevents the link from being followed
  $(this).closest('li.first-level').toggleClass('yourClass') // 
         .siblings('li.first-level').removeClass('yourClass');
});

Check out this interactive example on JSFiddle

Answer №2

This code snippet accomplishes all the desired tasks:

$("ul.secondLevel a").click(function () {
    $("#FirstLevel>li").removeClass("blue");
    $(this).parents("ul.secondLevel").parent().addClass("blue");
});

Here is the link to test it out: http://jsfiddle.net/abc123/

Answer №3

Below you will find the resolution :

When a click event is triggered on any anchor tag within an li element with the class 'secondLevel', 
the following jQuery function will be executed:
   $('#FirstLevel > li').removeClass('selected');
   $(this).parents('.secondLevel').parent().addClass('selected');

Answer №4

If you have set an Id for your initial list, you can easily locate the element by using a selector like this:

$(".subLevel a").on("click", function() {
    event.preventDefault();
    $("#TopLevel li").toggleClass("updatedStyle");
});

Answer №5

give it a shot

jQuery(this).closest('ul').addClass('customStyle');

Alternatively:

jQuery(this).closest('ul').addClass('customStyle');

Answer №6

Yet another response is presented here

const sample = $('li li,li li li')
console.log(sample)
            sample.click(function(){
   $(this).parents('ul').closest('li').addClass('kaka');
});

Check out the jsfiddle example

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

Guide on how to optimize an ajax call in the browser to prefetch JSON data

One scenario I am dealing with involves initiating multiple ajax calls upon page load. The first call fetches data in JSON format from the server, and subsequent user interactions trigger further ajax requests that require database queries to process the J ...

The setting `ensureCleanSession: true` doesn't appear to be effective when included in the capabilities for Internet Explorer 11

Currently, I am testing a login/logout application with the help of protractor. One challenge I am facing is dealing with a popup that appears after each login/logout scenario. In order to ensure the popup appears after each login, I need to reset the IE ...

StealJS Module Repathing Techniques

There seems to be an issue with my setup, so I welcome all inquiries. I am utilizing an npm package called xrm-mock for a MS CRM mocking framework. Here is how I have configured it: steal.config({ meta: { "dependencyModule": { deps ...

Issue with AnimeJS Motion Path causing element to deviate from desired SVG path

I'm attempting to use an SVG element and the AnimeJS library to make the orange marker follow the course of this RC car race track. https://i.stack.imgur.com/8FKHC.png Despite my efforts, I am encountering strange and undesirable outcomes. At times ...

Node JS GET request using fetch stops displaying console outputs after a certain duration

I am currently working on building a calendar application using node, mongodb, html, css, and javascript. The main goal is to allow users to input dates as events which can be displayed dynamically. I am facing an issue where, upon trying to retrieve these ...

Buttons in HTML function properly on desktop but are ineffective on mobile devices

My website is almost complete, but I am facing some challenges with the mobile version. All buttons that use JavaScript are not functioning properly, whereas buttons with simple links work perfectly fine. This issue doesn't occur on Chrome when using ...

Terminate the ongoing PHP script execution

Is there a way to terminate the current PHP script? For instance: page.php <?php require('./other-page.php'); ?> <h4>this text is always displayed</h4> other-page.php <?php if($_GET['v'] == 'yes&ap ...

JavaScript nested arrays not functioning with .map()

I've encountered a problem while using the .map function in JavaScript to extract a nested array from an API response. Here is the JSON: [ { "id": 3787, "title": "Dummy title!", "start_time": "2020-04-25T16:54:00.000Z", ...

Ways to transform a poster into a clickable link in an HTML video

I am currently working on embedding an mp3 audio file in a browser, along with an accompanying image and a URL for redirection upon clicking. To achieve this, I have placed the mp3 file within a video tag and designated the image as a poster using the foll ...

When attempting to execute a script that includes document.write, it will not function as expected

Our web program is utilizing ajax and jquery, specifically Netsuite. I've been attempting to adjust elements on a page using document.ready and window.load methods in order to load an external script onto the page. Regardless of whether I load this ex ...

Having trouble with implementing the Drag API Function alongside Javascript Arrow Functions?

I've searched extensively for a similar question but couldn't find one, so I hope this is not a duplicate. Recently, I created a factory function to assist me with drag and drop functionality in my current project. However, I noticed varied beha ...

Issue of inconsistency: The element is not connected to the page's document

Although this question may be a duplicate, I have not been able to find a solution for it, which is why I am asking again. I am currently using Selenium with C# and encountering the above error in several tests that involve the same action on the same pag ...

Utilize selenium IDE to retrieve a specific portion of text and save it as a variable

I am trying to figure out how to extract the number 694575 from a text using Selenium Ide and store it in a variable for future use. Here is the text I am working with: <div class="loginBoxTitle">Edit Exhibition Centre - 694575, Exhibition Center1&l ...

Tips for retrieving a td element from an HTML document

I have a variable containing HTML data and I need to extract a specific td element from it. When I use the alert(returnData) function, it displays the following output: <tr class='addedrow'> <td id="abc">DOM-001 <inpu ...

Error: The lambda response was not defined. Please review your function code. The response returned with a status of 500 in 583 milliseconds

https://i.sstatic.net/GUHr9.png I'm experimenting with Netlify and its Lambda function feature to execute a Node.js function. Following the guide at https://css-tricks.com/using-netlify-forms-and-netlify-functions-to-build-an-email-sign-up-widget/. ...

Tips for determining if a key is present in local storage:

I need to set a key value, but only if it doesn't already exist. In my component1.ts file, I am assigning the key and value in the constructor. However, I want to include a condition that this action should only be taken if the key is not already pre ...

Should the refresh button be displayed once the animation finishes?

Can anyone provide guidance on how to write jQuery code that will reveal a hidden button after an animation is finished? The button should also be able to refresh the animation for the user to watch again. Check out this fiddle: http://jsfiddle.net/rabela ...

Leveraging various libraries in React

My query revolves around a React application where I have integrated Material UI for only two components. Despite installing the entire Material UI library, will this lead to an increased bundle size for my application? Or does the build process only inc ...

How to target only the parent div that was clicked using jQuery, excluding any

I have attempted to solve this issue multiple times, trying everything I could find on Google and stack overflow without success. At times I am getting the span element and other times the div - what could be causing this inconsistency? $(".bind-key"). ...

Positioning the footer to sit at the bottom of my webpage, leaving a pleasing margin at the top

One technique I frequently use to ensure my footer stays at the bottom of my page is by utilizing an empty div. Here's how the code looks: <body> <div id="canevas"> <article>My website's content</article> ...