I use these JavaScript-code to change classes in my script:
var toggleDirection = function() {
group.classList.toggle('left-to-right');
group.classList.toggle('right-to-left');
}
In my example there a only two classes to change but could be also multiple classes ...
So therefore: Does anyone know a way to write the example less redundant?
Answer. Yes, you can toggle multiple classes using a single . toggleClass() call. To do so, you can separate the class names with spaces.
To specify multiple classes, separate the class names with a space, e.g. <span class="left important">. This allows you to combine several CSS classes for one HTML element.
An element is usually only assigned one class. The corresponding CSS for that particular class defines the appearance properties for that class. However, we can also assign multiple classes to the same element in CSS.
To add multiple classes to an element, select the element and pass multiple classes to the classList. add() method, e.g. box. classList. add('bg-blue', 'text-white') .
No it is not possible using Element.classList
API directly. Looking at API you can read:
toggle ( String [, force] ) When only one argument is present: Toggle class value; i.e., if class exists then remove it, if not, then add it. When a second argument is present: If the second argument is true, add specified class value, and if it is false, remove it.
Reference here.
You could potentially write your own "utility" function (in vanilla JS) which does what you want, below a very simple demonstrative example which work on top of the classList
API:
var superToggle = function(element, class0, class1) {
element.classList.toggle(class0);
element.classList.toggle(class1);
}
And you call it in this way:
superToggle(group,'left-to-right', 'right-to-left');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With