JavaScript className

Summary: in this tutorial, you will learn how to use the JavaScript className property to manipulate CSS classes of an element.

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

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>

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

let menu = document.querySelector('#menu');
console.log(menu.className);

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:

let menu = document.querySelector('#menu');
menu.className += ' new';
console.log(menu.className);

Output:

'vertical main new'

In practice, you’ll use the classList to add a new class to the existing classes of an element:

let menu = document.querySelector('#menu');
menu.classList.add('new');
console.log(menu.className);

Output:

'vertical main new'

To completely overwrite all the classes of an element, you use a simple assignment operator. For example:

element.className = "class1 class2";

To get a complete list of classes of an element, you need to access the className property:

let classes = element.className;

Because the class is a keyword in JavaScript, the name className is used instead of the class.

Also the class is an HTML attribute:

<div id="note" class="info yellow-bg red-text">JS className</div>

while className is a DOM property of the element:

let note = document.querySelector('#note');
console.log(note.className);

Output:

info yellow-bg red-text

An element has another property that helps you better manipulate its CSS classes called classList.

Summary #

  • The className property returns a space-separated list of classes of an element as a string.

Quiz #

Quiz

Understanding className Property

5 questions

Test your understanding of the className property and its usage in JavaScript

Was this helpful?