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
How to Install Node on Windows, macOS and Linux
Create an RSS Reader in Node
Getting Started with Electron
How to Serve Static Files with Nginx and Docker
Best Visual Studio Code Extensions for 2022
How to deploy a Node app using Docker
Learn how to use v-model with a custom Vue component
Using Puppeteer and Jest for End-to-End Testing
Getting User Location using JavaScript's Geolocation API
Creating a Twitter bot with Node.js
Building a Real-Time Note-Taking App with Vue and Firebase
