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
element.classList;
Example . Number of classes
Finding the number of element classes:
<p id="elem" class="www ggg zzz"></p>
let elem = document.querySelector('#elem');
let length = elem.classList.length;
console.log(length);
The code execution result:
3
Example . Looping through classes
Let's derive element classes one by one:
<p id="elem" class="www ggg zzz"></p>
let elem = document.querySelector('#elem');
let classNames = elem.classList;
for (let className of classNames) {
console.log(className);
}
The code execution result:
'www'
'ggg'
'zzz'
See also
-
the
classList.add
method
that adds a given class -
the
classList.remove
method
that removes a given class -
the
classList.contains
method
that checks a given class -
the
classList.toggle
method
which toggles a given class