Skip to content

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

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

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