className
Introduction to the JavaScript className
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 concatenate 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:
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.
Last updated