63
Work with the CSS classes of an element
2021-04-21 - JavaScript
1// JS Tip of the Day
2// Work with the CSS classes of an element
3
4// <p id="hero" class="steel-wing">Batman</p>
5
6let elem = document.querySelector('#hero');
7
8// Add multiple classes
9elem.classList.add('dark-knight', 'caped-crusader');
10// class="steel-wing dark-knight caped-crusader"
11
12// Remove multiple classes
13elem.classList.remove('steel-wing');
14// class="dark-knight caped-crusader"
15
16// Toggle a class
17elem.classList.toggle('dark-knight');
18// class="caped-crusader"
19
20elem.classList.toggle('dark-knight');
21// class="dark-knight caped-crusader"
22
23// Replace a class
24elem.classList.replace("caped-crusader", "batsy");
25
26// Check if an element has a class
27if (elem.classList.contains('dark-knight')) {
28 console.log("I'm the night!");
29}
30
31// Get the number of classes
32console.log(elem.classList.length); // 2
#JStipoftheday