JavaScript className

Created with Sketch.

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

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

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

Code language: JavaScript (javascript)

Output:

'vertical main new'

Code language: JavaScript (javascript)

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

Code language: JavaScript (javascript)

Output:

'vertical main new'

Code language: JavaScript (javascript)

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

element.className = "class1 class2";

Code language: JavaScript (javascript)

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

let classes = element.className;

Code language: JavaScript (javascript)

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>

Code language: HTML, XML (xml)

while className is a DOM property of the element:

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

Code language: JavaScript (javascript)

Output:

info yellow-bg red-text

 

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.

Leave a Reply

Your email address will not be published. Required fields are marked *