classList
DOM API:A very convenient manner of adding and removing classes is the classList
DOM API. This API allows us to select all classes of a specific DOM element in order to modify the list using javascript. For example:
const el = document.getElementById("main");_x000D_
console.log(el.classList);
_x000D_
<div class="content wrapper animated" id="main"></div>
_x000D_
We can observe in the log that we are getting back an object with not only the classes of the element, but also many auxiliary methods and properties. This object inherits from the interface DOMTokenList, an interface which is used in the DOM to represent a set of space separated tokens (like classes).
const el = document.getElementById('container');_x000D_
_x000D_
_x000D_
function addClass () {_x000D_
el.classList.add('newclass');_x000D_
}_x000D_
_x000D_
_x000D_
function replaceClass () {_x000D_
el.classList.replace('foo', 'newFoo');_x000D_
}_x000D_
_x000D_
_x000D_
function removeClass () {_x000D_
el.classList.remove('bar');_x000D_
}
_x000D_
button{_x000D_
margin: 20px;_x000D_
}_x000D_
_x000D_
.foo{_x000D_
color: red;_x000D_
}_x000D_
_x000D_
.newFoo {_x000D_
color: blue;_x000D_
}_x000D_
_x000D_
.bar{_x000D_
background-color:powderblue;_x000D_
}_x000D_
_x000D_
.newclass{_x000D_
border: 2px solid green;_x000D_
}
_x000D_
<div class="foo bar" id="container">_x000D_
"Sed ut perspiciatis unde omnis _x000D_
iste natus error sit voluptatem accusantium doloremque laudantium, _x000D_
totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et _x000D_
quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam _x000D_
voluptatem quia voluptas _x000D_
</div>_x000D_
_x000D_
<button onclick="addClass()">AddClass</button>_x000D_
_x000D_
<button onclick="replaceClass()">ReplaceClass</button>_x000D_
_x000D_
<button onclick="removeClass()">removeClass</button>_x000D_
_x000D_