CSS Class Manipulation with Vanilla JavaScript
Tags: javascript, css, beginners, html
Published: 2020-11-01 17:34:21

Today we'll talk about a basic feature of JavaScript, but one that can be employed to achieve a lot of different effects on your site. One of the goals of this series is to help budding web developers leave jQuery behind. A common task to use jQuery for is CSS class manipulation: adding, removing, toggling, or otherwise switching classes on an HTML element. Doing all these things in vanilla JavaScript is easy! JavaScript has a built in way to handle the classes at `Element.classList`.

# Access Classes on an Element

The `classList` property on an HTML element provides all we need to count classes on that element, add or remove them, toggle classes on and off, and swap classes for one another. Calling `Element.classList` will return a read-only list of the element's class attributes. Like an array, we can count the number of classes present with `classList.length`.

```javascript
// First we need to grab an HTML element
const myElement = document.getElementById('my-element');

// Then count how many classes attributes it has
console.log(myElement.classList.length);
```

## Add a Class

Though `Element.classList` is read-only, it still provides several methods that we can use to manipulate its value. We can call `.add()` to add a class to the element.

```javascript
// Add a class called 'my-class' to the element
myElement.classList.add('my-class');
```

## Remove a Class

We can call `.remove()` to remove a class from the element if it's present. If the class we name isn't there, that's okay.

```javascript
// Check for a class called 'my-class' and remove it
myElement.classList.remove('my-class');
```

## Add or Remove Multiple Classes

If we want to add or remove multiple classes as once, we can achieve this in two different ways. If all our class names are individual strings, we can just feed them as arguments into `classList.add()` or `classList.remove()`. If are class names are compiled in an array, we can use the spread syntax to pass the array in as a single argument.

```javascript
// Remove a couple individual classes by name
myElement.classList.remove('my-class', 'your-class');

// Alternatively, start with an array of class names
const classes = ['her-class', 'his-class', 'their-class'];
// Use the spread syntax in this case
// To use it, put three periods ... before the array name
// Now we can add every class in the array to the element
myElement.classList.add(...classes); 
```

## Toggle a Class

We can also call `.toggle()` and name a class to add it if it's not already on the element, and remove it if it was already on the element.

```javascript
// Toggle on a class named 'my-class'
myElement.classList.toggle('my-class');

// Toggle 'my-class' right off again
myElement.classList.toggle('my-class');
```

We can customize `classList.toggle()` by adding a second argument after the class name. This argument should be a conditional test that will evaluate to either true or false. If the result is true, the designated class will be added; if the result is false, the designated class will be removed.

```javascript
// Declare an integer to use in our conditional test
let myInt = 0;

// Toggle class on if the integer is greater than or 
// equal to 0
myElement.classList.toggle('my-class', myInt >= 0);

// We can change our integer to change the result of our
// conditional test
myInt = -1;

// The same toggle line now toggles our class off
myElement.classList.toggle('my-class', myInt >= 0);
```

## Replace One Class with Another

We can choose one class to replace with another class. Just pass the classes as two arguments to `classList.replace()`. First pass the class to swap out, then pass the class to swap in.

```javascript
// Replace 'my-class' with 'your-class'
myElement.classList.replace('my-class', 'your-class');
```

# `className`

Without a doubt, `Element.classList` is the best way to add and remove classes from an HTML element. It's very similar to the approach you'd use to accomplish the same tasks in jQuery, so if you're leaving behind your jQuery crutches in favor of vanilla JavaScript, this will be an easy transition. Using `classList` is probably preferable, however there is another way to access the class attributes on an element. You can also achieve this using `Element.className`. This property will return a string with the names of all classes on the element, separated with spaces. It's what you'd see if you looked at the element's HTML: one string--potentially with multiple class names--set to the element's `class` attribute.

```javascript
// Imagine we have this HTML element
<span id="my-span" class="text-white">Element</span>

// We can grab this element in JavaScript
const mySpan = document.getElementWithId('my-span');

// We can get and set the assigned class attributes via the 
// className property
console.log(mySpan.className);
mySpan.className = 'text-white border-white';
```

# A Few Ideas

Now that we've delved into the capabilities of `Element.classList`, try everything out and see if you can find some useful applications for these little techniques. You might use `classList.toggle()` to show and hide a menu using CSS classes. You might highlight a selected option in a list of options by using `classList.add()` or `classList.remove()` on each option. You might let users change themes on your site by calling `classList.replace()` as they select the next theme. `Element.classList` provides a powerful set of building blocks for you to create simple, succinct, yet sturdy solutions as you develop. It's a great example of how HTML, CSS, and JavaScript can work together to great effect without any additional libraries.