What is the best way to apply an active class to the parent li element when selecting an item within it? I want to achieve this effect

$(function() {
    var pgurl = window.location.href.substr(window.location.href
            .lastIndexOf("/") + 1);
    $("#nav ul li a").each(function() {
        if ($(this).attr("href") == pgurl || $(this).attr("href") == '')
            $(this).addClass("active");
    });

});

Here is the JavaScript code I am using to add the active class to the list item. It works perfectly, but I want the parent list item to also get an active class when selecting an item within a dropdown list.

<%@include file="header.jsp"%>
<div id="nav">

    <ul>
        <li class="headerFont"><a href="index.jsp"><b>HOME</b></a></li>
        <li class="headerFont"><a href="link.jsp"><b>HOW TO
                    DONATE</b></a></li>
        <li class="headerFont"><a class="tangina" href="#"><b>DONATE</b></a>
            <ul>
                <li class="headerFont"><a href="link2.jsp"><b>DONATION
                    CENTER <img id="arrow" src="img/arrow.png" />
                    </b></a></li>
                <li class="headerFont"><a href="link3.jsp"><b>HOW ELSE
                    CAN I DONATE? <img id="arrow" src="img/arrow.png" />
                    </b></a></li>
            </ul></li>
        <li class="headerFont"><a href="#"><b>GET DONORS</b></a></li>
        <li class="headerFont"><a href="#"><b>ABOUT BLOOD</b></a>
            <ul>
                <li class="headerFont"><a href="Bfacts.jsp"><b>BLOOD
                    FACTS <img id="arrow" src="img/arrow.png" />
                    </b></a></li>
                <li class="headerFont"><a href="news.jsp"><b>NEWS <img
                    id="arrow" src="img/arrow.png" /></b></a></li>
                <li class="headerFont"><a href="faqs.jsp"><b>FAQS <img
                    id="arrow" src="img/arrow.png" /></b></a></li>
            </ul></li>
        <li class="headerFont"><a href="about.jsp"><b>ABOUT US</b></a></li>

        <li class="headerFont"><a href="login.jsp"><b>LOG IN</b></a>
            <ul>
                <li class="headerFont"><a href="#"><b>REGISTER <img
                    id="arrow" src="img/arrow.png" /></b></a></li>
            </ul></li>

    </ul>

</div>
<div class="triangle"></div>
<div class="triangle2"></div>

Answer №1

Revise this line

$(this).addClass("active");

to

$(this).closest('li').addClass('active');

Using the closest method instructs jQuery to search for the closest li element in the DOM hierarchy. This targets the nearest parent.


An enhanced approach to slicing href strings:

**Check out this fiddle

Here is a more precise string slicing function:

/* start of code...*/
var pgurl = sliceString(window.location.href);
/*... rest of code */

function sliceString(s) {
    s = s.split("").reverse().join("");
    if (s.indexOf('/') === 0){
        s = s.substring(1);
    }
    s = s.substring(0, s.indexOf('/'));
    return s.split("").reverse().join("");
}

With this method, any trailing / character is eliminated, providing a more accurate retrieval of the target url.


Modification, the second:

If you want to select all parents, you can utilize the parents() selector as follows:

$(this).parents('li').addClass('active');

Another demo example


Final touch:

The third solution provided does identify the li containing the clicked a element, along with its parent li elements. Note that the top-level li (headerFont in your demonstration) includes all child li items, not just the clicked one. If you only wish to style the text for DONATE, adjust your CSS like so:

nav > ul > li.active b,
nav > ul > li > ul li.active {
  /* ACTIVE STYLES */
}

These CSS selectors combined will target the top-level b element in your navigation, as well as any non-top-level li element that was clicked.

Answer №2

$(this).closest().toggleClass('active');

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

When utilizing a node.js TCP socket to receive and send modified data, the functionality only operates successfully on the initial attempt

I am attempting to create a node.js TCP socket that will receive data, modify it, and then send it back. I found a helpful example on Stack Overflow here: . The example works perfectly as is, but when I add my own code to send data back, it only works for ...

AngularJS: Embedding a webpage within a <div> container

I recently came across this question in STO, but unfortunately, I couldn't find a suitable answer. Currently, I am working with Angular 1.0 and sending an AJAX request to the server to retrieve a list of URLs in the following format: My challenge no ...

Reducing Time Series Data: Comparing Average vs Largest-Triangle-Three-Buckets Technique

Currently, I am utilizing Flot Charts to create line charts that display timeseries data. To streamline the visualization process and reduce the number of data points shown, I have implemented a downsampling technique by averaging data points within the s ...

Having trouble finding the correct output when searching in the table using regex

I am currently experiencing an issue with my code for searching. When I search the full text, it works fine but when I search for a middle character, it does not work as expected. For instance, searching for "apple" or "ap" works correctly, however, if I ...

Retrieving server information using AJAX in React

I've been attempting to utilize an AJAX call in order to fetch server data for my React Components. However, I'm encountering difficulties when it comes to displaying it with React as I keep receiving this error: Uncaught TypeError: Cannot read ...

How to filter an array in Angular 4 without the need for creating a new array and then displaying the filtered results within the same

In my collection of students, I have their names paired with their academic outcomes. studentResults = [ {name: 'Adam', result : 'Passed'}, {name: 'Alan', result : 'Failed'}, {name : 'Sandy', result : &ap ...

submit multiple images simultaneously

I'm attempting to upload multiple photos simultaneously using XMLHttpRequest. if(files.length <= 6) { for(var i = 0; i < files.length; i++) { var formData = new FormData(); formData.append('action', 'upload ...

Updating an object with AngularJS

Let's consider the code snippet below: var absenceType = {name: 'hello'}; this.newAbsenceType = angular.copy(absenceType); After making changes to this.newAbsenceType, you want to apply these changes to the original object. I have explore ...

showing a loading spinner while sending an ajax request, patiently awaiting the response, and preventing any further interactions on the page

On my page, I am utilizing multiple ajax calls to load specific parts of the response. However, I need to display a spinner on the section where the ajax call is being made to indicate that content is loading. Is there a way to create a universal method th ...

Using Express.js to serve simple SVG files (Technique involving Cheerio.js)

My goal is to manipulate SVGs before sending them through Express.js. The code snippet I am using is as follows: app.get("/iconic/styles/:style/:base/:icon", function (req, res) { var style = req.params.style; var base = req.params.base; var i ...

React throws a "ReferenceError: indexedDB is not defined" but surprisingly, it still manages to function properly

I utilized yarn to install idb-keyval By utilizing the following code, I imported it: import { set } from 'idb-keyval'; Then, I assigned a value to a variable using the following code snippet: set('hello', 'world'); Althou ...

Three columns with the first column having a flexible width

On various coding forums, I've come across multiple examples using floats, but none have provided a solution for my specific issue. I have three column divs with varying widths - the first column is dynamic while the other two are fixed. Looking for a ...

Flashing text compatibility across all browsers

I'm looking for a way to create text that blinks on all major web browsers. Initially, I attempted using the <blink> HTML tag, but unfortunately, it only works in Mozilla Firefox. Next, I experimented with CSS: <style> .blink {text-deco ...

Accessing a distinct element of e.parameter

I've implemented a Google App Script on my website that automatically writes form data to a spreadsheet upon submission. With multiple forms on the site, I want all their data to go to the same Spreadsheet but different 'Sheets' (tabs at th ...

take a paragraph element outside of a container div

In my ASP project, I have incorporated JavaScript and CSS code that I obtained from JonDesign's SmoothGallery demo website. Now, I am trying to move the p tag containing the summary out of the div. Here is the current code snippet: <div id="myGall ...

I am having trouble grasping the concept of CSS and the first-child selector

I am having an issue with the first-child selector in CSS. I have two divs with the same class, each containing an image and a paragraph element. When I use the .div-class:first-child {margin:10} rule, the margin is only applied to the paragraph in the fir ...

Deactivate a div based on a Razor variable in ASP.NET MVC4

Is there a secure method to disable a div based on a Razor variable in ASP.NET MVC 4.0? I attempted using a CSS class, but it was easily bypassed with developer tools. .disableddiv { pointer-events: none; opacity: 0.4; } Any advice on how to effectively ...

Is there a problem with the way divs are being displayed when using jQuery to show the first 12 elements with the class "hide-show"?

I am encountering a problem with displaying data using the jQuery slice() and show() methods to reveal dynamically generated divs from a PHP function. The code is as follows: <style> .hide-show { display :none; } </style> <div class="c ...

Error code E401 is being encountered with npm, indicating either an incorrect password has been provided or the

My Node version is 10.15.0 and my NPM version is currently at 6.8.4. After updating npm to 14.16.0 and node to 7.6.2, I encountered the following error - npm ERR! code E401 npm ERR! Incorrect or missing password. npm ERR! If you were trying to log in, ...

Initializing start scripts in the package.json file

When launching my react app locally, I need to execute three commands: cd react-web npm run postinstall export REACT_APP_CUSTOMER_ENVIRONMENT=xxx npm start After running these commands, the application server starts on localhost:3000. For the start script ...