How to Change Button Class in Javascript

 

In this tutorial, you will learn how to change button class in javascript.  Change in class of an element represents change in state of the element.  Generally, you want to change button class on hover, but in this tutorial, we will change it on click just for the sake of simplicity.

In javascript, each element has classList property and this property has two methods add() and remove()Add() method is for adding class and remove() method for removing class. In the following example, we are simply adding and removing .blue and .red class on button click.  Please have a look over HTML, CSS, and Javascript code given below.

 

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
    
</head>
<body>
    <div>
        <button class="btnRed">Red</button>
        <button class="btnBlue">Blue</button>
        <button class="btn blue">My Button</button>
    </div>

    <script src="script.js"></script>
</body>
</html>

 

CSS:

body {
    text-align: center;
}

div {
    display: inline-block;
}

.btnRed, .btnBlue {
    padding: 5px 10px;
    margin-top: 10px;
}

.btn {
    padding: 10px 30px;
    margin-top: 20px;
    display: block;
    color: #fff;
}

.blue {
    background-color: blue;
}

.red {
    background-color: red;
}

 

Javascript:

let btnRed = document.querySelector('.btnRed');
let btnBlue = document.querySelector('.btnBlue');
let myButton = document.querySelector('.btn');


btnRed.addEventListener('click', () => { 
    myButton.classList.remove('blue');
    myButton.classList.add('red');
});

btnBlue.addEventListener('click', () => { 
    myButton.classList.remove('red');
    myButton.classList.add('blue');
});

 

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •