Clue Mediator

How to set an HTML element’s class using JavaScript

📅February 15, 2022

In this article, we will show you how to add / remove / toggle an HTML element’s class using JavaScript. There are two different properties called `className` and `classList` to modify the class of an HTML element in JavaScript.

Checkout more articles on JavaScript

Let’s consider the following HTML element for demonstration of the `className` property.

<h1 class="greeting">Hello Clue Mediator!</h1>

Get class name

const output = document.querySelector('h1').className;
console.log(output);
// Output: greeting

Set class name

document.querySelector('h1').className = 'title';

const output = document.querySelector('h1').className;
console.log(output);
// Output: title

The classList methods

Let’s talk about the `classList` methods to add, remove, toggle and replace the class. Use the following HTML element for demonstration.

<h1 class="greeting title">Hello Clue Mediator!</h1>

Add Class

Use the `classList.add()` method to add the class.

document.querySelector('h1').classList.add('first');

const output = document.querySelector('h1').classList.value;
console.log(output);
// Output: greeting title first

Remove Class

Let’s use the `classList.remove()` method to remove the class.

document.querySelector('h1').classList.remove('title');

const output = document.querySelector('h1').classList.value;
console.log(output);
// Output: greeting

Toggle Class

Now use the `classList.toggle()` method to toggles a given class on an object.

document.querySelector('h1').classList.toggle('active');
console.log(document.querySelector('h1').classList.value);
// Output: greeting title active

document.querySelector('h1').classList.toggle('active');
console.log(document.querySelector('h1').classList.value);
// Output: greeting title

Replace Class

Use the `classList.replace()` method to replace the class.

console.log(document.querySelector('h1').classList.value);
// Output: greeting title

document.querySelector('h1').classList.replace('title', 'first');

console.log(document.querySelector('h1').classList.value);
// Output: greeting first

That’s it for today.
Thank you for reading. Happy Coding..!! 🙂