Clearing a classList (with the JavaScript Spread Operator) Bookmark

Previously I have mostly used toggling, adding oder removing classNames from a classList with JavaScript. As these names suggest, they work with classList.toggle('className'), classList.add('className') and classList.remove('className'). For a recent project, I wanted to empty the complete classList of all its className tokens, which made me wonder what the best way to do so would be.

Just like the ways to Rome, there are multiple ways to remove all of your classNames in a class attribute, which all yield the same result. Let's have a look at the possibilities:

First, it is possible to toggle a className, which removes the className if it exists and otherwise adds ist to the classList. Yet this didn’t solve my problem.

element.classList.toggle('is-hidden');

One simple way to completely remove all tokens is to set the class attribute with setAttribute to an empty string, like so:

element.setAttribute('class', '')

Another option is to iterate over all the classNames in the classList and remove the first className as long as classNames can be found. By looking at the following code, I’m not sure why I would pick this, just for the amount of code required. Yet it works absolutely fine.

var classList = element.classList;
while (classList.length > 0) {
   classList.remove(classList.item(0));
}

What I didn’t know is that with ES6, the spread operator (which consists of three periods) offers another simple way to clear a classList. The spread operator description says: “Spread syntax can be used when all elements from an object or array need to be included in a list of some kind.“ This is exactly what was needed in this case.

For my classList example with the spread operator, the syntax also is a one-liner, as compact as the first example above:

element.classList.remove(...element.classList);

From a quick search on the performance difference between setAttribute and using the , it seems that the latter is slightly slower, but performance is not an issue for what I’m using it for.

I hope this has been helpful and thanks for reading this far. The documentation lists lots of other helpful cases for use of the spread operator, it’s worth checking out.

Update:
Thanks to Šime Vidas via Twitter here‘s the probably simplest one-liner that again does the same thing:

element.className = ''