Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Shivamyadav's avatar

JavaScript active navbar link?

How to add some css of tailwind using java script to the html attributes. html

<a href="http://localhost:8888" class="home">Home</a>

my code

document.querySelector('.home').addEventListener('click', function() {
    document.querySelector('.home').classList.add('bg-red-400')
});

by using my this code i can add a single class and and for only on click event once the events occurs it doesn't stay for the long period of the style.... some soultions

0 likes
3 replies
AddWebContribution's avatar

@shivamyadav can you write briefly about this i'm not able to understand it do you need a link active in red colour or what ? while clicking on the link if you want active that link then you can follow below code

  document.querySelector('.home').addEventListener('click', function() {
      document.querySelector('.home').classList.add('bg-red-400')
      document.querySelector('.home').classList.add('active')
 });
tisuchi's avatar

@shivamyadav Just another variation.

// Select all navigation links
const links = document.querySelectorAll('.home');

// Loop through each link
links.forEach(link => {
  link.addEventListener('click', function() {
    // Remove the active class from all links
    links.forEach(link => link.classList.remove('bg-red-400'));
    // Add the active class to the clicked link
    this.classList.add('bg-red-400');
  });
});
Shivamyadav's avatar

@tisuchi doesn't work same as my code is working.. Even it doesn't loop to the next element..

Please or to participate in this conversation.