Search code examples
javascriptdomdomtokenlist

What's the difference between className and classList.value?


Before you mark this answer as duplicate, I'm talking about "classList.value", not "classList".

What are the differences between:

element.className = 'main';
element.classList.value = 'main';

They can both "get and set the value of the class attribute of a specified element" (MDN's description of what className does).

I noticed the difference in performance seems very little (run it multiple times).

So, is there a difference?

I'm asking partially for curiousity, but also because everywhere I look it seems "className" is favoured - according to MDN's Browser compatibility it did come before classList.value.

.className is often recommended for setting the class list or clearing it. But.classList is also recommended when toggling, adding, removing. So, why not use .classList.value for consistency?


Solution

  • everywhere I look it seems .className is favoured

    Sure. It's shorter, simpler, faster, and - as you noted - supported by more (older) browsers. So there's hardly any reason to use .classList.value.

    But .classList is also recommended when toggling, adding, removing. So, why not use .classList.value for consistency?

    The class list is used when interacting with (toggling/adding/removing) individual classes. It is much easier to use for that than doing string manipulation on .className, like in olden times when .classList was not yet available.

    It is rare in general to replace the whole list. You might do it to remove all class names, but when working with a classList of individual classes then you should really only operate on those that your piece of code is responsible for. In that case you won't use .value, so there's no consistency to achieve. The property mainly exists for completeness of the interface, and for other usages of DOMTokenLists.

    If you really exercise complete control over the whole list, and want to manipulate it all at once, then again .className is simpler and shorter.