简体   繁体   中英

How to change add and remove active class in JavaScript

I have navigation Bar where I want to add active class and remove it from a previous clicked list I think it's a basic thing but I'm new in javascript so i couldn't figure out the solution. I have code that works but the last and first list does not remove.

HTML CODE

<div id="icon-layout">
      <ul>
         <li>CLOTHING</li>
         <li>BAGS</li>
         <li>SHOES</li>
         <li>ACCESSORIES</li>
         <li>BEAUTY</li>
         <li>ABOUT US</li>
         <li>SERVICE</li>
      </ul>
    </div>

CSS

#icon-layout .active{
  background-color: #FF4136;
  color: white;
}

JAVASCRIPT

var activeclass = document.querySelectorAll('#icon-layout li');
   for (var i = 0; i < activeclass.length; i++) {
    activeclass[i].addEventListener('click', activateClass);
   }
function activateClass(e) {
    var previous = e.target.previousElementSibling;
    var next = e.target.nextElementSibling;
    e.target.classList.add('active');
    previous.classList.remove('active');
    next.classList.remove('active');
}
var activeclass = document.querySelectorAll('#icon-layout li');
   for (var i = 0; i < activeclass.length; i++) {
    activeclass[i].addEventListener('click', activateClass);
   }
function activateClass(e) {
    for (var i = 0; i < activeclass.length; i++) {
        activeclass[i].classList.remove('active');
    }
    e.target.classList.add('active');
}

You may loop through all elements and remove class before adding one

Try using JQuery as it would definitely make your task easier:

$('#icon-layout li').on('click', function() {
    $('.icon-layout li.active').removeClass('active');
    $(this).addClass('active');
});

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