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"]; B.classList.add(...clsa);
Now, my question is, how can I get a list of classes in A, in the form of
- I can do this by using
A.classNameproperty, then splitting it into an array.
Or I can simply append
B.className, as easily as:
B.className += A.className;
Or I can iterate components of
A.classListobject, 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:
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.