To add, remove or toggle element's class, first of all, we need to get this element. The most modern way is to use document.querySelector
. Javascript have element.classList property, which will return DOMTokenList collection attributes of the element. And that's how we can manipulate elements classes.
Add new class
To add new class, we need to use .add()
method:
document.querySelector(".someClass").classList.add('newClass');
Remove class
To remove class from element, we need to use .remove()
method:
document.querySelector(".someClass").classList.remove('newClass');
Toggle class
Lastly, to toggle class (remove, if class exist and add if the class doesn't exist), we need to use the .toggle()
method:
document.querySelector(".someClass").classList.toggle('newClass');
Add class to multiple elements at once
But what if we want to add specific class to all existing classes? We need to use different selector - document.querySelectorAll
, which will return a list of elements with class from parameter. Then, to add, remove or toggle class, we should use .forEach()
method.
document.querySelectorAll(".someClass").forEach((el) => {
el.classList.add('newClass');
});