You should know that using this property to set a value for the class attribute will replace the current value of this attribute no-matter how many names set there. So if you want to add a new class name or replace only one name (if they are multiple names in fact) you need to first get their values and use string methods to separate these values and replace the specific name with a new value. And then assign the old + the new value again to that class attribute.
Note: there’s a more advanced property called classList that basically does the same work but with more options. Basically, using the classList, makes the process of working with multiple class names super simple.
Element className Property Syntax:
element.className; element.className = new-value;
Element className Property Input Value.
We can use the className property to assign a new value for the `class` attribute of an element. For example, if there’s an element and we want to assign the value “red” to its class attribute, then we can simply assign this value to the className property and so the target element will get this value for its class attribute.
Note: if there are multiple class names we want to assign for this attribute, put them all in a pair of double quotation mark and separate them with white spaces.
For example: “className1 className2 className3”
Element className Property Return Value
The return value of this property is a string value that contains the current value assigned to the class attribute of the target element.
Also, if the target element does not have the class attribute, the return value of this property becomes an empty string.
How does Element className property work?
Here the button element doesn’t have the class attribute! But when we click the button, the createClick() method will be invoked and in that body, there’s a call to the className property which will get the value “red” as its value.
This means now the button element has the class attribute with the value “red” assigned to it.
Now because in the CSS style, we have set a background-color to red for any element in the page that has the class “red”, this button’s background now changed to the color red.
Note that here the button element has already the value blue assigned to its class attribute. But after the call to the className property to change the value, the old one (the blue value) was “replaced” with the value red.
Again: assigning a value to the className property will replace any value that is currently set for the class attribute of an element.
Note that here we’ve put a white-space before the new value for the class attribute of the button element. This is because we need a white space between the values of a class attribute.
Also, we’ve used += operator to not replace the old values but to add a new one instead.