Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use setAttribute to set multiple classes on an element?

Tags:

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"; 
like image 271
OVERTONE Avatar asked Jul 28 '11 14:07

OVERTONE


People also ask

How do you give an element multiple classes?

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.

Can you set multiple attributes at once JavaScript?

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.

How do you use setAttribute?

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() .


1 Answers

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).

like image 120
Quentin Avatar answered Oct 04 '22 07:10

Quentin