className
Last updated
Last updated
The className
is the property of an element that returns a space-separated list of CSS classes of the element as a string:
Suppose that you have the following ul
element:
The following shows the classes of the ul
element in the console window:
Output:
To add a new class to an element using the className
property, you can the existing class name with a new one:
The +=
operator concatenates newClassName
to the existing class list of the element. Therefore, you need to prefix the new class name with a space like this:
Output:
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:
Also the class
is an HTML attribute:
while className
is a DOM property of the element:
Output:
className
returns a space-separated list of classes of an element as a string.
In practice, you’ll use the to add a new class to the existing classes of an element:
Because the is a keyword in JavaScript, the name className
is used instead of the class
.
An element has another property that helps you better manipulate its CSS classes called .