classList property

The classList property contains pseudo-array of element CSS classes, and also allows you to add and remove element classes, check for a specific class among element classes.

We are talking about the class attribute, inside which you can write several classes separated by a space, for example www ggg zzz. With classList you can remove, for example, the class ggg without affecting other classes.

Syntax

javascriptelement.classList;

Example . Number of classes

Finding the number of element classes:

html<p id="elem" class="www ggg zzz"></p>
javascriptlet elem = document.querySelector('#elem');

let length = elem.classList.length;
console.log(length);

The code execution result:

javascript3

Example . Looping through classes

Let's derive element classes one by one:

html<p id="elem" class="www ggg zzz"></p>
javascriptlet elem = document.querySelector('#elem');
let classNames = elem.classList;

for (let className of classNames) {
  console.log(className);
}

The code execution result:

javascript'www'
'ggg'
'zzz'

See also