How to set an HTML element’s class using JavaScript
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.
1 | <h1 class="greeting">Hello Clue Mediator!</h1> |
Get class name
1 2 3 | const output = document.querySelector('h1').className; console.log(output); // Output: greeting |
Set class name
1 2 3 4 5 | 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.
1 | <h1 class="greeting title">Hello Clue Mediator!</h1> |
Add Class
Use the classList.add()
method to add the class.
1 2 3 4 5 | 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.
1 2 3 4 5 | 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.
1 2 3 4 5 6 7 | 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.
1 2 3 4 5 6 7 | 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..!! 🙂