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?

element.classList.add("dynamic-class");

//remove
element.classList.remove("dynamic-class");

use element.classList.add method.

var element = document.getElementById("div1");
element.classList.add("otherclass");

How to add a class to an element using JavaScript?

Using .className property – index.html

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

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 infinityknow.com.
Your valuable feedback, question, or comments about this Article are always welcome.
If you enjoyed and liked this post, don’t forget to share.