简体   繁体   中英

How can I active a link when click, and deactivate the others in javascript?

I'm trying to handle just one element when I click in the link, but when I click on another it doesn't remove the active to other links. Can anyone help me? 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've try some methods but with no result.

I think this is what you wanted. this code loops through all anchor elements when one is clicked and removes that active class from all of them, then adds the active class to the clicked element.

 let parentT = document.querySelector('.menu-item'); //PARENT let allEl = parentT.querySelectorAll('a'); // ELEMENTS INSIDE PARENT allEl.forEach(elem =>{ elem.addEventListener('click', (event) => { event.preventDefault(); allEl.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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM