Programmatically manipulating CSS classes
When working with Javascript there will be times when we need to change the CSS we apply to the web pages we're working on. Javascript provides two methods to manipulate an HTML element's classes: [className](https://developer.mozilla.org/en-US/docs/Web/API/Element/className) and [classList](https://developer.mozilla.org/en-US/docs/Web/API/Element/classList). For this post we'll concentrate in `classList` since it provides methods to manipulate the class attribute and it avoids the string manipulation that you'd have to do when working with `className`. `classList` is a **read-only** property that returns a live space-separated list of the class attributes of the element that we can manipulate using `classList` methods The classList methods are: [add()](https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList/add) : Adds one or more tokens to the element's class attribute, skipping duplicates [remove()](https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList/remove) : Removes the specified token from the list [replace()](https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList/replace) : Replaces the old token (the first parameter) with the new value (the second parameter) : If the old token doesn't exist, `replace()` will return false and **will not** add the second token to the class attribute [toggle()](https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList/toggle) : Cycles through states of the specified attribute : If the attribute exists then `toggle()` will remove it and return false : If the attribute doesn't exist, `toggle()` will add it and return true [contains()](https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList/contains) : Searches the class attribute. Returns true if the class is present and false otherwise ## Examples I created a Codepen to illustrate how `classList` works. The HTML defines the structure of the demo. The box with id of `myBox` will change based on the buttons we push. Each button exercises a different method of `classList` discussed earlier. `scan` doesn't have a button because we used in the Javascript without producing visible results. ```html
content