How to toggle HTML classes in vanilla JavaScript
I’ve done this a million times in jQuery, simply by using toggleClass()
on a jQuery object.
You can achieve the same effect in vanilla JS:
x
2
1
let el = document.getElementById("main");
2
el.classList.toggle('menu-open');
Also, there’s a second parameter that forces the toggle to always remove or always add. So you could use that to add some simple logic.
xxxxxxxxxx
1
2
1
let el = document.getElementById("some-button");
2
el.classList.toggle('menu-open', someBoolean);