How can I use setAttribute to set multiple classes on an element?
if you're looking to append (not destory current classes), I would do
element.className = element.className + " anotherclass yetanotherclass"
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";
The attribute className
is a space-separated list of values.
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).