How to add CSS class using JavaScript

Adding CSS class dynamically by using .className property in JavaScript

0 269

In this tutorial, I am going to explain the procedure of adding the CSS class using JavaScript. The need for adding CSS by JavaScript is that sometimes, we need to add style in a dynamic manner, which means that styling should kick in upon the user interaction. Inline style rules of CSS do not fulfill this requirement of dynamic styling.

I will be using the .className property to deploy the dynamic interaction on the web-page. The .className property can be used to retrieve or set a class to the HTML element.

For retrieving the class we can use:


While for setting a new class we have to use:

HTMLElementObject.className = class


<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<title>setProperty() Method using JavaScript </title>
 width: 50%;
 margin: 0px auto;

 .addCSS {
          color: blue;
          font-size: 3.0rem;

   <div class="main-div">
      Setting className property using JavaScript

     <p id = "text-data">
      Hello World!

   <button onclick = "addClass()">
     function addClass() {
       var addelement = document.getElementById("text-data");
       addelement.className += "addCSS";



Before Clicking the Button

After Clicking the Button

I hope with the above tutorial, you have learned the dynamic styling by using CSS with JavaScript.

Please do share your comments and suggestions to make this space even better. Subscribe to our website for more stuff.


Leave a Reply

    Waiting for your comments