How can I use setAttribute to set multiple classes on an element?
Solution 1
Just set the attribute as normal. It just sets the attribute to whatever string you pass it, it isn't aware of any special rules for how the value gets handled.
The attribute takes a space separated list of classes so:
element.setAttribute("class","class1 class2");
However… older versions (I think 7 and lower) of Internet Explorer have serious bugs in their setAttribute
implementation — so don't use it. Use the className
property instead.
element.className = "class1 class2";
Note, also, that these are HTML classes. They uses beyond the application of styles. There is no such thing as a CSS class (although there are class selectors, other selectors, rule sets and properties, all of which have been (incorrectly and confusingly) called "classes" at some time or another).
Solution 2
The attribute className
is a space-separated list of values.
Solution 3
Try this:
document.getElementById("MyElement").className = "class1 class2";
(notice the space instead of comma between the two names)
Or, if you want to add on to the classes already there:
document.getElementById("MyElement").className += " class1 class2";
Solution 4
if you're looking to append (not destory current classes), I would do
element.className = element.className + " anotherclass yetanotherclass"
Solution 5
It is safe to use element.className += "classname"
so that the new class gets appended to the list of classes already present.
OVERTONE
3000 people view, 500 people favourite, 5 closed it all down.
Updated on July 28, 2022Comments
-
OVERTONE almost 2 years
How can I set an element to have multiple classes?
Initial attempt:
element.setAttribute("class","class1","class2"); element.className="class1 , class2"; element.class="class1 , class2";