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!
Managing PHP Dependencies with Composer
Getting Started with Svelte
Create an RSS Reader in Node
How to deploy a .NET app using Docker
How to deploy an Express app using Docker
How to Scrape the Web using Node.js and Puppeteer
Getting Started with Handlebars.js
Creating a Twitter bot with Node.js
Building a Real-Time Note-Taking App with Vue and Firebase
Getting Started with Vuex: Managing State in Vue
Setting Up a Local Web Server using Node.js
How To Create a Modal Popup Box with CSS and JavaScript
