html – Style classList vs className in JavaScript-ThrowExceptions

Exception or error:

I have two DOM elements, A and B, and want to get all style classes from A, and append them to B.

I understand that I can append new classes to element, without wiping existing ones, this way:

B.classList.add("cls1", "cls2", "cls3");

or this way:

var clsa = ["cls1", "cls2", "cls3"];

Now, my question is, how can I get a list of classes in A, in the form of clsa array?

  • I can do this by using A.className property, then splitting it into an array.
  • Or I can simply append A.className to the B.className, as easily as:

    B.className += A.className;
  • Or I can iterate components of A.classList object, 0: … N:.

The second one looks most natural. However, there’s this feeling that the classList, not the className, is the preferred “home” for style classes of an object. Is that right?

And if so, is there any elegant and clear way to do so, without resorting to using className?

Maybe something like:

How to solve:

Unobvious, but appears to work in Chrome:



You can first try to cast classList to an array like it is answered in Why doesn't .includes() work with .classList? , and then append using spread operator.


Leave a Reply

Your email address will not be published. Required fields are marked *