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

Implement a custom placeholder feature for InputNumber in Blazor

I have a question about adding a placeholder to the InputNumber component. I attempted the following code but unfortunately, it did not work as expected. //Code behind public int? Hour { get; set; } //razor page <EditForm Model=&quo ...

What is the process for transferring an image from a cloud function request to the vision API?

Just set up a Google Cloud Function with an HTTP endpoint. I want to pass an image to this endpoint and have it sent all the way to the Vision API (which is already set up) and then receive the response back. So, in essence: image in POST request -> C ...

Disregard any unnecessary lines when it comes to linting and formatting in VSC using EsLint and Prettier

some.JS.Code; //ignore this line from linting etc. ##Software will do some stuff here, but for JS it's an Error## hereGoesJs(); Is there a way to prevent a specific line from being considered during linting and formatting in Visual Studio Code? I h ...

Getting a user's group name from Azure Active Directory in an Angular application - a step-by-step guide

I have connected to Azure directory using ng2-adal (https://github.com/mazhisai/ng2-adal-QuickStart) and successfully obtained a group id in the format: "groups":["4ba2649e-20d2-40f4-a406-2ed897686403","43e19f05-c077-4716-b001-0ffb0d75fff8"]. Is there a w ...

Dynamic shopping cart with Vue.js

Currently, I am working on a shopping cart project using Vue.js and Vuetify. I need help figuring out how to capture the boolean value true or false and adjust the total price in the amount based on whether it is true or false. Any suggestions? <v-con ...

Tips for converting file byte code to file form data

From one folder I am retrieving a file and uploading it to another server. However, when I extract the file from the first folder, I receive a byte code representation of that file. The API for uploading the file to the second folder requires FormData as a ...

"Upon calling an asynchronous method within another method, it appears that no progress is being displayed

I've created a `node-js` `db.js` class that retrieves an array of data for me. //db.js const mysql = require('mysql'); var subscribed = []; const connection = mysql.createConnection({ host: 'localhost', user: 'root' ...

Updating the $_GET parameter using JQuery when a button is clicked

I'm working on implementing a feature where a series of buttons can update the $_GET['year'] variable on my website. These buttons should function across different pages within my website, such as: example.com example.com/?search=foo exa ...

Javascript's event.keyCode does not capture the Backspace or Delete keys in Internet Explorer

Looking to detect when the Backspace and Delete keys are pressed using javascript/jQuery, I have the following code: $("textarea[name=txt]").keypress(function(e){ var keycode = e.keyCode ? e.keyCode : e.which; if(keycode == 8){ // backspace ...

I keep encountering a 404 error whenever I try to access a controller method using Ajax. What could be causing this

In my ValidationController, there is a method named EmailExist. I made an ajax call to the following URL: $.ajax({ type: "POST", url: "/Validation/EmailExist", data: { 'Email': $('#Email').val() }, success: fun ...

Cannot find the appended element in an AJAX call using jQuery

Within the code snippet, .moneychoose is described as the div in moneychoose.jsp. Interestingly, $(".moneychoose") cannot be selected within the ajax call. $("input[name='money']").on("click", function() { if ($("#money").find(".moneychoose" ...

A React-based frontend solution designed exclusively for managing data structures and databases

Challenges with Product Management In my React App, the shop features products sourced solely from a JSON file as an external API, all managed on the frontend. Recently, I encountered a product with limited availability - only 20 pieces in stock. I am uns ...

Maintaining an active link in a navigation list: A guide for Twitter Bootstrap

How can I make a link appear active when clicked, and keep it active while the user is on that page? (Using Symfony2 with Twitter bootstrap) <ul class="nav nav-list"> <li class="active"> <a href="/link1">Link</a> </li> &l ...

Is Angular 4 failing to set headers properly or is Express.js searching in the wrong place?

When interacting with an Express.js API, I encountered a issue regarding the handling of auth tokens. The problem arose when sending the token in the request headers using Angular 4 compared to Postman. In Postman, setting the header named 'Authorizat ...

Text positioned on the right side of the image, appearing to hover above

After finding a helpful example on Stack Overflow, I successfully implemented a similar layout for product boxes in a JSFiddle. I then replicated the CSS and HTML almost exactly on my Wordpress blog, but encountered an issue where the title, description, a ...

Pictures in Windows 7 have shifted to the left

After a recent migration to the Windows 7 operating system at my company, I encountered an issue. While using the same Visual Studio 2010 master file that was working fine on my Windows XP machine, I noticed that all the images below were now shifted to t ...

Tips for successfully executing child_process.exec within an ajax request

On a server that I have access to but not ownership of, there is a node js / express application running on port 3000. Various scripts are typically executed manually from the terminal or via cron job. My goal is to have a button on the client-side that tr ...

What is the best method for arranging various react components in sync?

I am striving to achieve a specific style. My current code looks like this: <Box display="flex" flexDirection="row" alignItems="center" width={1}> <Box flexGrow="1"> <Typography variant="h6 ...

Is there a way to search for multiple items using just one search term?

On my app, there is a search bar that currently only looks up data for one specific attribute. For example, if I type in "Hammer," it only searches for Tool names. Now, I need to expand the search functionality to accommodate different types of strings. F ...

A guide on selecting the best UI container based on API data in React using TypeScript

I have been developing a control panel that showcases various videos and posts sourced from an API. One div displays video posts with thumbnails and text, while another shows text-based posts. Below is the code for both: <div className=""> &l ...