Element.classList
Add, remove, toggle, and check for classes on an element.
let elem = document.querySelector('#sandwich');
// Add the .turkey class
elem.classList.add('turkey');
// Remove the .tuna class
elem.classList.remove('tuna');
// Toggle the .tomato class on or off
// (Add the class if it's not already on the element, remove it if it is.)
elem.classList.toggle('tomato');
// Check if an element has the .mayo class
if (elem.classList.contains('mayo')) {
console.log('add mayo!');
}
⏰ Preorder my new course on Web Components! Want to learn how to build Web Components from scratch, master best practices, and more? Preorder today and get $100 off of the launch price.
Find this useful? You can support my work by purchasing an annual membership.