How to Toggle an Element's Class in Pure JavaScript?

Let's suppose we have the following HTML element, and we wish to toggle the class "foo-bar" on the element:

<div id="example" class="foo-bar baz"></div>

Using Element.classList

Element.classList returns a DOMTokenList (which is a live collection of the class attributes of an element). We can use the DOMTokenList.toggle() method to remove class from the list if it exists, or add the class to the list if it doesn't. For example:

document.getElementById('example').classList.toggle('foo-bar');

Both, Element.classList and DOMTokenList.toggle(), have good browser support (going back to IE10).

Using Element.className

Converting Element.className into an Array and Toggling a Class:

If you wish to support browsers below IE10, then simply converting the string of class names returned by Element.className into an array of class names might help. It would make it easier to check if a class exists or not, and accordingly the class can be added or removed from the list of classes, for example, like so:

function toggleClass(elem, className) {
    const classNamesArr = elem.className.split(/\s/);
    const index = classNamesArr.indexOf(className);

    if (index === -1) {
        classNamesArr.push(className);
    } else {
        classNamesArr.splice(index, 1);
    }

    elem.className = classNamesArr.join(' ');
}

const elem = document.getElementById('example');

toggleClass(elem, 'foo-bar');
console.log(elem.className); // output: 'baz'

toggleClass(elem, 'foo-bar');
console.log(elem.className); // output: 'baz foo-bar'

The toggleClass() function does not erroneously partially match "foo" for "foo-bar". For example:

toggleClass(elem, 'foo');
console.log(elem.className); // output: 'baz foo-bar foo'

toggleClass(elem, 'foo');
console.log(elem.className); // output: 'baz foo-bar'

Array.prototype.indexOf() is not supported in IE versions below 9. For supporting browsers below IE9, you can use a polyfill of Array.prototype.indexOf() (for example, like the one at MDN).

Find & Replace Using Regular Expression:

Another approach can be to use regular expressions to find a match and accordingly add or remove it from the string of class names returned by Element.className. For example:

function toggleClass(elem, className) {
    const classNames = elem.className;
    const regex = RegExp('(^|\\s)' + className + '(\\s|$)');

    elem.className = (regex.test(classNames))
        ? classNames.replace(regex, '')
        : (classNames + ' ' + className);
}

const elem = document.getElementById('example');

toggleClass(elem, 'foo-bar');
console.log(elem.className); // output: 'baz'

toggleClass(elem, 'foo-bar');
console.log(elem.className); // output: 'baz foo-bar'

The toggleClass() function does not erroneously partially match "foo" for "foo-bar". For example:

toggleClass(elem, 'foo');
console.log(elem.className); // output: 'baz foo-bar foo'

toggleClass(elem, 'foo');
console.log(elem.className); // output: 'baz foo-bar'

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.