How to Add a CSS Class to an Element using JavaScript
Table of Contents
The easiest way to customize and control the front-end UI of a webpage is to utilize CSS classes.
Sometimes, you need to add a class on an element on the fly, and for that we can use JavaScript.
In this post, we'll learn how to use JavaScript to add a CSS class to an element.
How to add a CSS class to an element using JavaScript
To add a CSS class to an element, let's first look at some example HTML:
HTML<div class="my-element">My element</div>
Let's say we want to add the class my-class
to the element with the class my-element
.
We want the result to look like this:
HTML<div class="my-element my-class">My element</div>
First, we'll need to query the DOM for this element using the querySelector()
method:
JAVASCRIPTconst myElement = document.querySelector(".my-element");
Now that we have the element, we can use the built-in classList
property to add the class.
This property is an object that contains a list of all the classes on the element.
It contains an add
method that we can use to add a class to the element.
JAVASCRIPTconst myElement = document.querySelector(".my-element");
myElement.classList.add("my-class");
When this code runs, the markup will be updated to look like this:
HTML<div class="my-element my-class">My element</div>
If you want to add multiple classes to this element, you can still use the add
method, just pass in multiple classes as arguments:
JAVASCRIPTconst myElement = document.querySelector(".my-element");
myElement.classList.add("my-class", "another-class", "yet-another-class");
This will add all three classes to the element, so the result looks like this:
HTML<div class="my-element my-class another-class yet-another-class">My element</div>
Conclusion
In this post, we learned how to use JavaScript to add a CSS class to an element.
Simply use the classList
property to access the list of classes on the element, and then use the add
method to add a class to the element.
Thanks for reading!
- Getting Started with Express
- Best Visual Studio Code Extensions for 2022
- How to deploy a PHP app using Docker
- How to deploy a Deno app using Docker
- Getting Started with Deno
- How to deploy an Express app using Docker
- Getting Started with Sass
- Learn how to use v-model with a custom Vue component
- Getting Started with Handlebars.js
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting User Location using JavaScript's Geolocation API
- Getting Started with Vuex: Managing State in Vue