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:

element.classNameCode language: CSS (css)

Suppose that you have the following ul element:

<ul id="menu" class="vertical main">
   <li>Homepage</li>
   <li>Services</li>
   <li>About</li>
   <li>Contact</li>
</ul>Code language: HTML, XML (xml)

The following shows the classes of the ul element in the console window:

let menu = document.querySelector('#menu');
console.log(menu.className);Code language: JavaScript (javascript)

Output:

vertical main

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