add method of the classList object
The add method of the
classList
object allows you to add CSS
classes to an element.
Syntax
element.classList.add(class);
Example
Let's add the class kkk to an element:
<p id="elem" class="www ggg zzz"></p>
let elem = document.querySelector('#elem');
elem.classList.add('kkk');
The code execution result:
<p id="elem" class="www ggg zzz kkk"></p>
Example
Let's add the class zzz to an
element, which is already in the element
- nothing will happen, since duplicate
classes are not added:
<p id="elem" class="www ggg zzz"></p>
let elem = document.querySelector('#elem');
elem.classList.add('zzz');
The code execution result:
<p id="elem" class="www ggg zzz"></p>
See also
-
the
classList.removemethod
that removes a given class -
the
classList.containsmethod
that checks a given class -
the
classList.togglemethod
which toggles a given class