javascript add class – How to add a class to an element using JavaScript?

javascript add class – This method is used to add a class name to the selected element. A quick tutorial on how to add, remove and toggle classes in JavaScript. Using the classList method.

javascript add class

adding a class name can be done in a couple of ways. there are 2 Ways JavaScript Add Class To The Elements

How to add a class to a given element?



use element.classList.add method.

var element = document.getElementById("div1");

How to add a class to an element using JavaScript?

Using .className property – index.html

<!DOCTYPE html>  
add class name using JavaScript  
.dhara {  
font-size: 30px;  
background-color: yellow;  
color: blue;  
border: 2px dotted red;  
<h2>  Welcome :)  </h2>  
<p id = "first">  
Welcome to the  
<p> Click the bellow button to display the effect. </p>  
<button onclick = "getData()">  
Add Class  
function getData() {  
var a = document.getElementById("first");  
a.className = "dhara";  

Don’t Miss : Dynamically AddClass CSS Click Using JQuery

Also Read This πŸ‘‰   Laravel File Upload Progress Bar Example Tutorial

I hope you get an idea about javascript add class.
I would like to have feedback on my
Your valuable feedback, question, or comments about this Article are always welcome.
If you enjoyed and liked this post, don’t forget to share.