1var element = document.getElementById('element');
2element.classList.add('class-1');
3element.classList.add('class-2', 'class-3');
4element.classList.remove('class-3');
1// getting the target element
2var myElement = document.querySelector('#myElement');
3
4// example for addding some-class to the element
5myElement.classList.add('some-class');
6
7// multiple classes can be added like this
8myElement.classList.add('one-class', 'one-more-class');
9
10// example for removing any class from the element
11myElement.classList.remove('any-class');
1var someElement= document.getElementById("myElement");
2 someElement.className += " newclass";//add "newclass" to element (space in front is important)
1const div = document.createElement('div');
2div.className = 'foo';
3
4// our starting state: <div class="foo"></div>
5console.log(div.outerHTML);
6
7// use the classList API to remove and add classes
8div.classList.remove("foo");
9div.classList.add("anotherclass");
10
11// <div class="anotherclass"></div>
12console.log(div.outerHTML);
13
14// if visible is set remove it, otherwise add it
15div.classList.toggle("visible");
16
17// add/remove visible, depending on test conditional, i less than 10
18div.classList.toggle("visible", i < 10 );
19
20console.log(div.classList.contains("foo"));
21
22// add or remove multiple classes
23div.classList.add("foo", "bar", "baz");
24div.classList.remove("foo", "bar", "baz");
25
26// add or remove multiple classes using spread syntax
27const cls = ["foo", "bar"];
28div.classList.add(...cls);
29div.classList.remove(...cls);
30
31// replace class "foo" with class "bar"
32div.classList.replace("foo", "bar");