0

I have some <li> elements inside <ul> element in the navigation bar , There is a class called "active" that has some properties to define the active page , I want to add this class to one of them when it is clicked and remove it from this <li> siblings using Javascript without any frameworks just pure Javascript .

<ul class='tabs'>
   <li class='active'>Home</li>
   <li>About</li>
   <li>Contact</li>
</ul>

So when another page name is clicked the 'active' class is removed from the others and added to that page name.

0

3 Answers 3

2

Try the code below:

[].forEach.call(document.querySelectorAll('.tabs li'), function(el) {
    el.addEventListener('click', function(e) {
         var activeItem =  document.querySelector(".tabs li.active");
       if(activeItem)
       {
         activeItem.classList.remove("active");
       }
       el.classList.add("active");
    });
});

code edited in case you don't have any initial active items

1

A list of link nodes can be selected using document.querySelector and an event listener attached for click events.

const links = document.querySelectorAll('.tabs li');

function activate(links) {
  links.forEach(function(link) {
    link.classList.remove('active');
  });
  this.classList.add("active");
}

links.forEach(function(link) {
   link.addEventListener('click', activate.bind(link, links));
});
.active {
  color: red;
}
<ul class='tabs'>
   <li class='active'>Home</li>
   <li>About</li>
   <li>Contact</li>
</ul>

1

This would be the most efficient way to do it using only 1 event listener on the parent UL:

document.querySelector('.tabs').addEventListener('click', function(e) {

    var current = e.target; // the item clicked

    // all li items
    var items = current.parentElement.querySelectorAll('li');
    
    // go through each li and remove .active unless current
    Array.prototype.slice.call(items).forEach(function (item) {
        item.className = (item === current) ? 'active' : '';
    });
});
.active {
  color: red;
}
<ul class='tabs'>
   <li class='active'>Home</li>
   <li>About</li>
   <li>Contact</li>
</ul>

Not the answer you're looking for? Browse other questions tagged or ask your own question.