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 TypeScript
Managing PHP Dependencies with Composer
How to Serve Static Files with Nginx and Docker
How to deploy a .NET app using Docker
How to deploy a Deno app using Docker
Getting Started with Sass
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 Moment.js
Creating a Twitter bot with Node.js
Using Axios to Pull Data from a REST API
