How to add a class name to an element with JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

To add a class name to an element with JavaScript, the code is as follows −


 Live Demo

<!DOCTYPE html>
<meta name="viewport" content="width=device-width, initial-scale=1" />
   .newStyle {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
      width: 100%;
      padding: 25px;
      background-color: rgb(147, 80, 255);
      color: white;
      font-size: 25px;
      box-sizing: border-box;
      text-align: center;
<h1>Adding className with JavaScript Example</h1>
<button class="btn">Click here</button>
<h2>Click the above button to add className to below div</h2>
<div id="sampleDiv">
This is a DIV element.
   document.querySelector(".btn").addEventListener("click", addClassName);
   function addClassName() {
      var element = document.getElementById("sampleDiv");


The above code will produce the following output −

On clicking the “Click here” button −

Published on 08-May-2020 17:01:23