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

Related searches

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?

The following should work; granted that these class-names are defined in your CSS and some elements on the current page have these classNames:

var toggleDirection = function()
{
    var ltr, rtl, lst, cls;

    ltr = 'left-to-right';
    rtl = 'right-to-left';
    lst = [].slice.call(document.getElementsByClassName(ltr));

    lst = ((lst.length > 0) ? lst : [].slice.call(document.getElementsByClassName(rtl)));

    lst.forEach
    (
        function(node)
        {
            cls = node.getAttribute('class');

            if (cls.indexOf(ltr) > -1)
            { cls.split(ltr).join(rtl); }
            else
            { cls.split(rtl).join(ltr); }

            node.setAttribute('class', cls);
        }
    );
}

Vanilla JavaScript: Is there a way to toggle multiple CSS-classes in , This code is well-done, clear and rigourous, and it works fine. But I would not work exactly the same. Error processing. I agree with your doubts,� 7 Vanilla JavaScript: Is there a way to toggle multiple CSS-classes in one statement? Apr 11 '16 6 JavaScript: Augmenting types - Purpose of “return this” [duplicate] Apr 16 '15

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

JavaScript function for to toggle multiple CSS-classes at once , Vanilla JavaScript: Is there a way to toggle multiple CSS-classes in one statement? - javascript. Instead of having two, three, or more CSS rules that do the same thing (set the color of something to red, for example), you use a single CSS rule that accomplishes the same thing. The secret to this efficiency-boosting tactic is the comma. Christopher Robbins / Photodisc / Getty Images How to Group CSS Selectors

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 }
<p class="one">Click to toggle one class</p>
<p class="two">Click to toggle two classes</p>

Toggle Multiple Classes onclick - javascript, I am trying to toggle multiple classes onclick using vanilla Javascript. What i am trying to do is How do i change the visibility of multiply objects in an array. Currently I am To hide this element you can use the jQuery function hide or css. Like the all the stores. I was able to make dynamic content with this line: document. Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, PHP, Python, Bootstrap, Java and XML.

You can extend the DOMTokenList object with the following multiToggle

if (window["DOMTokenList"]) //check if DOMTokenList is an existing object.
{
//multitoggle
DOMTokenList.prototype.multiToggle = function()
{
    if (arguments.length > 0) // there needs to be at least one object
    {
        for (argument in arguments) //loop all arguments
        {
            var argument = arguments[argument];
            //All primitives are allowed as input (Symbol not included). If not a primitive, raise error.
            if (Object.prototype.toString.call(argument) !== "[object Undefined]" && Object.prototype.toString.call(argument) !== "[object Null]" && Object.prototype.toString.call(argument) !== "[object String]" && Object.prototype.toString.call(argument) !== "[object Number]" && Object.prototype.toString.call(argument) !== "[object Boolean]")   
            {
                throw new SyntaxError;
            }
            else
            {
                if (this.contains(argument)) //check if classList contains the argument.
                {
                    this.remove(argument); //if so remove
                }
                else
                {
                    this.add(argument); //if not add
                }                   
            }
        }
    }
    else
    {
        throw new Error("The argument is not optional");
    }
    return undefined; //return undefined as with add and remove.
}       
}

multiToggle does not have the force ability of the original toggle. It just turns class names on and off for as many arguments as supplied.

Warning, expanding fixed Objects can cause troubles in the future . When an object gets deprecated or changed your functionality could break, requiring to more maintenance.

Vanilla JavaScript: Is there a way to toggle multiple CSS-classes in one statement? | Q&A ProDevsBlog. Yaphi Berhanu demonstrates two different methods for adding and removing a CSS class to DOM elements with vanilla JavaScript. there’s only one way). When you can control CSS classes

just use the map array.

like

['left-to-right', 'right-to-left'].map(v=> group.classList.toggle(v) )

In order to show the div we will need to add a Javascript function. We will pass the ID attribute of the Div to the function. Basically this means that we can use this one function to show or hide more than one Div on the same page. Below is the Javascript code that we will add the the Head section of the page.

Notably, these are the names of the two CSS classes discussed in Step 1. In Step 2, these two class references have become property names in a JavaScript object. The values associated with these

Is there a way to make the link disappear once it’s been clicked on? So, there’s a link that says “click to read more” or something like that. When you click on it, the div appears (which I’ve been able to achieve already by including the display:none; tag) and at the same time the div appears, the “click to read more” link disappears

Comments
  • You can create your own prototype for Element => jsfiddle.net/rayon_1990/2noyz7zf
  • This just toggles through everything and leaves it on the last one. I dont think this is what OP wanted.
  • I think you misunderstand the way classList.toggle() works. It does allow for a second argument, but that is used as a conditional for the first argument, which holds the class to toggle. It does not allow for two classes to be toggled at once. See developer.mozilla.org/en-US/docs/Web/API/Element/classList
  • @agrm Thanks for the correction. I will edit my answer shortly so that it doesn't mislead others.
  • @rayalois22 Can you please edit the answer? It doesn't work!