Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vanilla JavaScript: Is there a way to toggle multiple CSS-classes in one statement?

Tags:

javascript

css

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?

like image 630
cluster1 Avatar asked Apr 11 '16 09:04

cluster1


People also ask

Can you toggle multiple classes JavaScript?

Answer. Yes, you can toggle multiple classes using a single . toggleClass() call. To do so, you can separate the class names with spaces.

How do I use multiple CSS classes on a single element?

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.

Can an element have multiple CSS classes?

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.

How do you add multiple classes to a classList?

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') .


1 Answers

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');
like image 152
GibboK Avatar answered Sep 19 '22 15:09

GibboK