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";
To specify multiple classes, separate the class names with a space, e.g. <span class="left important">. This allows you to combine several CSS classes for one HTML element.
To set multiple attributes for an element at once with JavaScript, we can call the element's setAttribute method. const setAttributes = (el, attrs) => { for (const [key, val] of Object.
Element.setAttribute() Sets the value of an attribute on the specified element. If the attribute already exists, the value is updated; otherwise a new attribute is added with the specified name and value. To get the current value of an attribute, use getAttribute() ; to remove an attribute, call removeAttribute() .
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With