I use these JavaScript-code to change classes in my script:
var toggleDirection = function() {
group.classList.toggle(\'left-to-right\');
group.classLis
For anyone looking for a short answer, you can do this on one line using the rest parameter introduced in ES6/ES2015:
const toggleCSSclasses = (el, ...cls) => cls.map(cl => el.classList.toggle(cl))
This is pretty close to @attacomsian's answer, but taking advantage of the fact that the rest parameter will return an array - no matter how many arguments is being passed to the function. Which means we can skip the part where we detect whether we're working with a string or an array.
const toggleCSSclasses = (el, ...cls) => cls.map(cl => el.classList.toggle(cl));
const one = document.querySelector(".one");
one.addEventListener("click", () => {
toggleCSSclasses(one, "class1");
});
const two = document.querySelector(".two");
two.addEventListener("click", () => {
toggleCSSclasses(two, "class1", "class2");
});
.class1 { text-decoration: underline }
.class2 { background: steelblue }
Click to toggle one class
Click to toggle two classes