Sidebar navigation with live class links

My xsl document contains a navigation sidebar with multiple anchors. I attempted to implement a script recommended in a Stack Overflow post, but the CSS style modification is not working as expected.

<script>
     <![CDATA[
       document.querySelectorAll("#menu-hermeneutics li > a").forEach(a => {
          a.addEventListener("click", () => {
              a.addClass('active'); 
          });
       });]]>
</script>
<ul id="menu-hermeneutics">
    <li><a href="#general-overview">General Overview</a></li>
    <li><a href="#context-overview">...</a></li>
    <li><a href="#result-overview">...</a></li>
    <li><a href="#clanA">...</a></li>
    <li><a href="#aff-clanA">...</a></li>
    <li><a href="#clanB">...</a></li>
    <li><a href="#aff-clanB">...</a></li>
    <li><a href="#DR">...</a></li>
    <li><a href="#clanUNK">...</a></li>                
</ul>

The included CSS code:

#menu-hermeneutics > .active {background-color: grey; color: white; font-weight: 700; margin-right: 100px; width: 200px; }

Your assistance in resolving this issue would be greatly appreciated. Thank you in advance.

Answer №1

Initially, the code

document.querySelectorAll("#menu-hermeneutics li > a")
will target all a tags and apply the class active when clicked. However, the subsequent CSS #menu-hermeneutics > .active is different. It specifically targets children of #menu-hermeneutics with the class active, but as you are using the child selector (>), it selects li elements, not a. If you want to style all children a elements only, you should use #menu-hermeneutics a.active. For more information, check out this link: here. I hope this clarifies things.

Answer №2

Special thanks to the helpful insights from @ThienHuynh and a coworker, the following is now the accurate code:

let links = document.querySelectorAll("#menu-hermeneutics li a");
  for (const link of links) {
    link.addEventListener("click", (e) => {
    let target = e.target;

    links.forEach(function(currentLink) {
        currentLink.classList.remove('active');
    });

      // Check if the target already has the .active class. If so, remove it. Otherwise, add it
      target.classList.toggle('active');
    })
    }

Please refer to my note below regarding the differences between > and &gt--this was the crucial issue in avoiding a bug.

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

What methods can be used to prevent polygon edge stitching artifacts from occurring on an HTML5 Canvas?

As I manage both parallel Flash and HTML5/Canvas renderers for the OpenHeatMap open-source project, I am encountering an inconsistency in the rendering of filled polygons with fractional coordinates between the two versions. A visible join appears along sh ...

Utilize separate production environments for each client on the NodeJS server to ensure seamless operation and

After conducting extensive research, I have been unable to find a solution to my current problem. I am operating a Node server with multiple environments (dev, test, demo, prod). The server is deployed on a Linux server in the production environment via a ...

Tips for excluding empty strings from the total length calculation

Issue: My input fields should turn into green buttons once the correct syllables are inserted. However, the problem lies in the fact that it determines correctness based on the length of my JSON data compared to what the user inputs. Even when my array con ...

The functionality to open the menu by clicking is experiencing issues

I'm attempting to replicate the Apple website layout. HTML structure: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" conte ...

Tips on incorporating an external JSON file into a javascript variable for global accessibility

I have been utilizing a JSON file in my project with the following structure: <script src="js/main.js"></script> <script> var data = {"bills":[{"id":1,"name":"DStv","reference":"SmartCard Number","logo":"bill\/logo\/24 ...

Comparison of Foundation5 source ordering: main content versus sidebar

I recently set up a layout with three columns using ZURB Foundation 5. The two sidebars are on the left and right, while the main content area is in the middle. While trying to follow the source ordering instructions in the documentation, I encountered so ...

Issues with the functionality of the mouseover event when multiple objects are being overlaid

Seeking assistance with implementing mouseover tooltip effects on a d3 graph. The circle appears above the line, but the issue arises when the mouse hovers directly over the line causing the tooltip to disappear. Is there a way to prioritize the circle ove ...

Error: Unable to locate the variable deleteChap

Utilizing Jquery to dynamically add elements to an element, I have included an onclick function to one of the <td> tags to trigger a function within the same file. Below is the code snippet for the element: let x = 0; let element = ` <td class=&q ...

Issues involving adding elements to an array in CSS, JS, and HTML

I am currently working on a module where exam information is stored in an array and passed to another JavaScript file using localStorage. However, I'm facing an issue where the previous exam data keeps getting overwritten despite using .push method. A ...

Adjust the size of a div element after updating its content using Mootools

I am currently utilizing mootools 1.2 on a basic webpage. There is a div that contains a form (referred to as formdiv) which is submitted through JS/ajax. Once the ajax request returns a "confirmation message" data, the formdiv updates accordingly. The is ...

What is the most effective method for integrating Bootstrap CSS into an Angular project?

When incorporating a Bootstrap CSS file into an Angular project that has already been added using yarn add <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f2909d9d868186809382b2c6dcc3dcc3">[email protected]</a>, th ...

"Emphasize menu items with an underline as you navigate through the

I am using Gatsby with React and have a navigation menu with links. I would like to make it so that when a link is clicked, a border bottom appears to indicate the current page, rather than only on hover. <ul className="men" id="menu"> ...

Building personalized Cron Jobs in Node.js - a step-by-step guide

What I Need I am looking to develop an email scheduling system where users can schedule emails to be sent at a specific time daily. The challenge lies in allowing each user to set their own sending time. How can I approach this for individual users? Curr ...

Ensuring that objects remain fixed in place regardless of window resizing is a common task in web development, often achieved through a

I've been attempting to create range sliders with boxes that display the slider's current value, but I'm having trouble getting them positioned correctly when the window size changes. Despite trying various solutions found online, I resorted ...

"Observed Issue: Ionic2 Array Fails to Update in HTML Display

I am struggling with updating an array in Ionic2 and Angular2. I have tried updating it on the front end but it's not working, even though it updates perfectly on the backend (ts) as confirmed by checking the console. I need assistance with this. Her ...

How can we verify in enzyme that the history.push method was called while utilizing withRouter and connect?

In a stateless React component, I am utilizing withRouter and connect. Within this component, there is a button that triggers a method in props provided by mapDispatchToProps. My goal is to create a test that verifies the button's action of calling h ...

What is the best way to incorporate a new field into an established JSON structure?

I have a JSON data set containing 10,000 unique records and I am looking to add another field with a distinct value to each record. What is the best way to achieve this? [ { _id: "5fffd08e62575323d40fca6f", wardName: "CIC", region: &quo ...

Tips for saving data after reading lines in Node.js

I am working on a project where I need to read data from an external text file into my function. How can I efficiently store each line of the file as a separate variable? const fs = require("fs"); const readline = require("readline"); const firstVariable ...

How do you implement radio button logic within an *ngFor loop?

When I populate options in a form with radio buttons, I am not seeing isChecked set to true when I select an option. Am I missing something in the following Angular code? app.component.html <div class="form-group"> <label>answerOption</la ...

What is the best way to include overflow-hidden in the image displayed by the tailblock component?

I have implemented the following Tailblock component, which is built on tailwind.css. My goal is to achieve a hover effect where the image scales up within its original dimensions. I want the image to zoom in without changing its height and width. I atte ...