Assigning active classes based on the href attributes of child <a> tags

I've created a navigation structure as follows:

<ul class="page-sidebar-menu">
  <li class="menu">        
    <a href="">
      <span class="title">Menu Item</span>
      <span class="arrow"></span>
    </a>    
    <ul class="sub-menu">
      <li>
        <a href="somehref">Sub Menu Item</a>
      </li>
    </ul>                   
  </li>
</ul>

In order to highlight the submenu link, I need to add an active class to '.submenu li'. Additionally, I want to add an active class to 'li.menu' based on the href of '.submenu li a'. I attempted to achieve this with the following code, but it's not functioning properly:

  $(function(){
    var current = location.pathname;
    current = current.substring(current.lastIndexOf('/'));
    $('.sub-menu li a').each(function(){
        var $this = $(this);
        if($this.attr('href').indexOf(current) !== -1){
            $('.sub-menu:parent').addClass('start active open'); //ISSUE
            $('.sub-menu li a:parent').addClass('active');
        }
    });

Answer №1

To correctly target the current anchor within the current iteration context, you must use this and then traverse to the desired parent element .sub-menu using .closest(). After that, add the necessary classes as follows:

 $('.sub-menu li a').each(function(){
    var $this = $(this);
    if($this.attr('href').indexOf(current) !== -1){
        $this.closest('.sub-menu').addClass('start active open'); //SOLUTION
        $this.addClass('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

Verifying that the code runs only once the changes to a monitored property have been successfully implemented in the user interface

When working with AngularJS, how can one ensure that code is executed only after a change to a watched property has fully taken effect in the UI? For instance, imagine that the visibility of a loading indicator is tied to the value of an isLoading propert ...

When using Wordpress AJAX, the Jquery component successfully sends the data, however the corresponding PHP function fails to execute

Trying to implement a jQuery function that triggers an AJAX call when a user clicks on a specific element. The goal is to extract the data value from this element, pass it to a PHP function, and execute the function using the received variable. While the j ...

Caution: Make sure to assign an object to a variable before exporting it as the default module

While working with react-redux, my root Reducer appears like this: import Customers from "./customers/reducer"; export default { Customers }; Recently, I encountered a warning saying: Assign object to a variable before exporting as module def ...

How can I ensure that the AppBar background color matches the color of the navigation bar?

Having trouble changing the background color of the <AppBar> in my project. Using the Container component to set a maximum screen size, but encountering issues when the screen exceeds this limit. The AppBar background color appears as expected while ...

What is the relationship between $.when, apply(), and $.done() within the scope of this function?

I recently received this function from a helpful SO user that allows for returning a variable number of jQuery $.get() requests. The initial part seems pretty straightforward, but I am struggling to understand how $.when(), apply(), and $.done() are inte ...

Why is ng-change not functioning properly, especially in conjunction with the Select element?

HTML <select ng-model="selectedName" ng-change="retrieveSelectedClass()" ng-options="(item.name||item) group by item.groupName for item in names" class="code-helper" id="code-helperId"> <option value="">Select Option</op ...

Footer not being pushed down by content in mobile view on page

Hello everyone, Can you assist me with a query, please? My form works perfectly fine in desktop view, but it gets cut off on mobile view and I'm unsure of the reason why. Here is my code: .upload-pic { position: absolute; max-width: au ...

Safari is currently experiencing compatibility issues with iPad, resulting in a malfunction

I encountered a unique issue with my most recent website project. The website is built on WordPress, and the custom theme I created is presenting an unexpected problem: Despite functioning perfectly on all browsers and devices, the site fails to display p ...

Capture video frames from a webcam using HTML and implement them in OPENCV with Python

While many may find it simple, I am facing a challenge in extracting video frames from HTML or JavaScript and utilizing them in my Python OPENCV project. I have a strong background in Python OPENCV and Deeplearning, but lack knowledge in HTML and JavaScr ...

Modifying the app.css file in the source tab of dev tools does not cause any changes in the DOM when working with a

Just starting out with react js here. While exploring developer tools in Chrome, I attempted to tweak some CSS in the elements panel and noticed the changes reflecting above in the DOM. However, when I navigate to the sources tab, I'm unable to modify ...

Align section titles to the right of the screen in Zurb Foundation 4

I'm in the process of incorporating sections to develop a navigation system on a basic webpage. However, I require it positioned on the right side of the screen. The default arrangement generated by Foundation with the use of "vertical-tabs" is "tabs ...

Paper.js: Is there a way to prevent canvas height and width from changing when the window is resized?

My canvas with paperjs is set up to resize dynamically when the window is resized. I appreciate any help in advance. HTML <canvas id="myCanvas" height="800" width="1000"></canvas> JS var Initialize = function () { var canvas = document ...

I'm not skilled in programming, so I'm not sure what the problem is with the code

While working on my Blogger blog, I encountered the need to add a fixed sidebar ad widget that would float along the screen. After trying multiple codes, I finally found one that worked. However, using the template's built-in variable functions led to ...

The state returned by React Redux does not meet the expected results

I recently implemented a like function on the backend using Node and MongoDB. This function successfully returns the post with an updated likes counter, which I tested using Postman. The post object contains properties such as likes, _id, by, createdAt, an ...

modifying the state in a stateless React component

Hello everyone! I am here trying to work with hooks and I'm not sure how to achieve my goal. Here is the code I have: import React, { useState } from 'react' import { useForm } from 'react-hook-form' import {useDispatch } from &a ...

What are some strategies to enhance the efficiency of this code and reduce repetition?

Here's an overview of the component in question export default () => { const { currentUser, logout } = useAuth(); const [sideBarOpen, setSideBarOpen] = useState(false); const theme = useTheme(); const classes = useStyles(); const isSmall ...

Is there a way for me to expand the dropdown menu?

My current dropdown looks like this. I'd like the dropdown menu to span across the screen, something like this: To create my dropdown, I am using https://github.com/angular-ui/ui-select2. AngularJS JQuery Select2 I'm not sure if there is an ...

I want to initiate a Python script by clicking a button on my HTML page with the help of Ajax

Here is my JavaScript code: function executePython() { alert("executed"); $.ajax({ url: "http://localhost:5000/app.py", type: "POST", ...

Utilizing Chart.js for generating a sleek and informative line graph

After executing a MySQL query, I obtained two tables named table1 (pl_pl) and table2 (act_act) with the following data: table1: label act_hrs Jan-19 7 Feb-20 8 Mar-20 9 table2: label pl_hrs Mar-20 45 Apr-20 53 I am looking to create a line cha ...

Is it achievable for a modal popup to automatically move to a specified location?

I need assistance with... Is it feasible to display an external webpage within a modal window and have that page automatically scroll to a specific section (such as an anchor point)? ...