0
How to toggle active class between list items with Javascript
A simple list <ul> <li class="active">one</li> <li>two</li> </ul> I want when i click on any one of these two, then Javascript add active class to it and remove it from the other item. It's simple with jQuery, but i want it with Javascript, thanks.
6 Réponses
+ 3
Emanuel Maliaño the issue is we don't use toggle class at all, we have to clear the previous active li and set the new active li, toggle class active won't solve the problem.
+ 1
You can do that with
element.classList.add('active')
element.classList.remove('active')
+ 1
// firstly, clear all li class name
document.querySelectorAll('ul li').forEach(li => li.style.className = '');
// next set the new select li
selectedLi.style.className = 'active';
Emanuel Maliaño your code only works on toggling the same element, which is not what Mohamed Salah wants.
0
Calviղ It is just a help, it is not all the code.✌
0
Calviղ You are right, i edit my answer
0
H