Search code examples
javascriptclickaddeventlistenertargethandle

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.


Solution

  • 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>