What is the best way to enable a link upon clicking while simultaneously disabling the others using JavaScript?

When I click on a link, I want to handle just that one element. However, when I click on another link, the active class is not being removed from the previous ones. Can anyone offer assistance with this issue? Here's my code:

let parentT = document.querySelector('.menu-item'); //PARENT
let allEl = parentT.querySelectorAll('a'); // ELEMENTS INSIDE PARENT

allEl.forEach(elem =>{   
  elem.addEventListener('click', (event) => { 
    event.preventDefault(); 
      event.target.setAttribute('class', 'active');
      if(event.target.classList == "active") { 
         console.log(event.target);

      }
  }); 
});

I have tried some methods but haven't achieved the desired result.

Answer №1

Here is the solution for your query. This script allows you to loop through all anchor elements and remove the active class from each of them when one is clicked, then adds the active class only to the clicked element.

let parentElement = document.querySelector('.menu-item'); //PARENT
let allElements = parentElement.querySelectorAll('a'); // ELEMENTS INSIDE PARENT

allElements.forEach(element =>{   
  element.addEventListener('click', (event) => { 
    event.preventDefault(); 
    allElements.forEach(el => {
        el.classList.remove('active');
    });
    event.target.classList.add('active');
  }); 
});
.active {
  color: red;
}
<div class="menu-item">
  <a href="#">Link 1</a>
  <a href="#">Link 2</a>
  <a href="#">Link 3</a>
  <a href="#">Link 4</a>
  <a href="#">Link 5</a>
</div>

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

Querying through a database containing 1 million <string Name, int score> pairs efficiently within sub-linear time

My JSON object holds 1 million pairs. var student = {[ { name: "govi", score: "65" }, { name: "dharti", score: "80" }, { name: "Akash", score: "75" },............. up to a million ...

Bokeh is having trouble loading from the CDN

I am currently attempting to embed a plot along with its data by utilizing autoload_static within a straightforward html page that I wish to view locally on my computer. According to the documentation, all I need to do is place the .js file in the specifie ...

Instructions for subtracting the value of a cell in column 22 from a cell in column 24 within the same row when a change trigger occurs utilizing Google Apps Script

I need help modifying the script below to only subtract the row on which the change is made, instead of subtracting all rows in the sheet when the on-change trigger executes. var sourceSpreadsheetID = '1r4e4BNKwsmdC2Ry93Mq-N49zj3DAZVpHG21TgTe0FWY&a ...

How can I achieve the same functionality as C# LINQ's GroupBy in Typescript?

Currently, I am working with Angular using Typescript. My situation involves having an array of objects with multiple properties which have been grouped in the server-side code and a duplicate property has been set. The challenge arises when the user updat ...

Extracting Client's True IP Address using PHP API

Utilizing the following api: I am able to retrieve country, city, and real IP address in localhost (127.0.0.1) successfully. However, when I implement this code on my website, it displays the server's address instead of the client's. How can I r ...

"Customize your map pins on Google Maps by updating the marker location through a

I am trying to update the position of a map marker based on a dropdown selection. Upon changing the dropdown option, I retrieve the latitude and longitude values and want to set these coordinates for my current marker. Here is the code snippet: $("#locati ...

Obtaining the final field with the $in operator in Mongoose

I need to retrieve all person records that fall within a time frame specified by start and end dates, and have a place ID of either 1 or 2. Below is the query I am using: Person.find({ time: { $gte: start, $lt: end ...

Solving the issue of overflowing in the animation on scroll library

I've recently started using a fantastic library called animation on scroll (aos) for my web development projects. This library offers stunning and visually appealing animations. However, I encountered an issue where it causes overflow problems in my H ...

Attempting to run the npm install command led to encountering a SyntaxError with an

Recently, I made some alterations to my npm configuration and ever since then, I have been consistently encountering the same error whenever I try to install various packages. It seems that due to a personal mistake in changing the npm settings, I am now u ...

Disable multiple buttons at once by clicking on them

What is the best way to disable all buttons in a menu when one of them is clicked? Here is my code: <div class="header-menu"> <button type="button"> <i class="fa fa-search" matTooltip="Filter"& ...

Why does the combination of "minus, space, minus" result in the "plus" operation?

When running the command 'node -e 'console.log(- -1)' it outputs 1, which is expected. However: When executing the command 'node -e 'console.log(1 - - 1)' it displays 2, which puzzles me. It seems like when subtracting a ne ...

What is the best way to make my if statement pause until a GET request finishes (GUARD) with the help of Angular?

I am currently working on implementing admin routes for my Angular app, and I have used a role guard to handle this. The code snippet below showcases my implementation: However, I would like the get request to finish executing before the if statement begi ...

An issue has arisen when trying to fetch and parse data using React and JavaScript

I am currently facing some challenges with fetching data from an API and displaying it using React. I have encountered errors and I am struggling with parsing the JSON response from the API. I believe that converting the response into an array may help res ...

Tips for avoiding infinite re-render loop when updating state in React/Next.js

I currently have a unique Next.js application that showcases randomly selected YouTube videos. The state within the app is structured as follows (managed by Redux): const state = { entities: { videos: { 'vidId1': { ...

Leveraging properties in computed Vue.js

I have a computed property that looks like this: display() { return this.labs.map(function(x, i) { return [x, this.plotDt[i]]; }); } This property receives data as props: props: ["plotDt", "labs"], Both plotDt and labs are ar ...

Infinite scrolling with Jquery: Loading dynamic content seamlessly from external websites

Hey there! I recently started using this cool jQuery plugin called jquery-endless-scroll. Here's a snippet of my code: $(function() { $('#list').endlessScroll({ pagesToKeep: 10, fireOnce: false, insertBefore: "#list div:first ...

Transferring information between an ASP web form page and an Angular2 application

Currently, I am working on a project that involves dealing with a legacy WebForms system. The system is gradually being updated to Angular 2, but the transition is happening incrementally. In order to effectively integrate information from the legacy sect ...

Struggling to integrate the c3 chart library with Angular, encountering loading issues

I've been attempting to utilize the c3 angular charts, but unfortunately nothing is displaying on my page. Despite checking for console errors and following a tutorial, I still can't seem to get anything to show up. I have cloned the git repo an ...

I can't seem to figure out what's causing this error to pop up in my coding setup (Tailwind + Next.js). It

I've been struggling with this problem for a week now and despite my efforts, I haven't been able to find a solution yet. However, I have made some progress in narrowing down the issue. The problem arises when I try to execute the yarn build comm ...

PHP and JavaScript both offer methods for escaping variables that are written in the syntax ${HOST}

How can I safely handle variables from the database like ${HOST}? This issue arises when code is posted within <pre><code> tags. If left as it is, an error occurs: Uncaught ReferenceError: HOST is not defined. In this specific context, usin ...