To add a new class to an element using the className property, you can concatenate the existing class name with a new one:
element.className += newClassName;
The += operator concatenatesnewClassName to the existing class list of the element. Therefore, you need to prefix the new class name with a space like this:
Output:
In practice, you’ll use the classList to add a new class to the existing classes of an element:
Output:
To completely overwrite all the classes of an element, you use a simple assignment operator. For example:
To get a complete list of classes of an element, you just need to access the className property:
Because the class is a keyword in JavaScript, the name className is used instead of the class.
Also the class is an HTML attribute:
while className is a DOM property of the element:
Output:
An element has another property that helps you better manipulate its CSS classes called classList.
Summary
className returns a space-separated list of classes of an element as a string.