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.

29th Jul 2020, 4:21 PM
Mohamed Salah
Mohamed Salah - avatar
6 Answers
+ 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.
29th Jul 2020, 5:03 PM
CalviŐČ
CalviŐČ - avatar
+ 1
You can do that with element.classList.add('active') element.classList.remove('active')
29th Jul 2020, 4:24 PM
Emanuel Maliaño
Emanuel Maliaño - avatar
+ 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.
29th Jul 2020, 4:28 PM
CalviŐČ
CalviŐČ - avatar
0
CalviŐČ It is just a help, it is not all the code.✌
29th Jul 2020, 4:46 PM
Emanuel Maliaño
Emanuel Maliaño - avatar
0
CalviŐČ You are right, i edit my answer
29th Jul 2020, 5:11 PM
Emanuel Maliaño
Emanuel Maliaño - avatar
0
H
14th Aug 2024, 5:12 AM
Vikki Kumar
Vikki Kumar - avatar