How to add CSS class using JavaScript
×

Adding CSS class dynamically by using .className property in JavaScript

1858

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:

HTMLElementObject.className

While for setting a new class we have to use:

HTMLElementObject.className = class

Code:

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

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

   </style>
 </head>
 <body>
   <div class="main-div">
   <center>
     <h1>
      Setting className property using JavaScript
     </h1>

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

   <button onclick = "addClass()">
      AddClass
   </button>
</center>
</div>
  <script>
     function addClass() {
       var addelement = document.getElementById("text-data");
       addelement.className += "addCSS";
      }

   </script>
 </body>
</html>

Output:

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.



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments