In previous post, I have provided working example of form validation using pure Javascript, now in this article, you will understand how to toggle class of an DOM element using Javascript only without using jQuery.

Toggle Class on button Click using Javascript

toggle-class-javascript-min.gif

In the first example, we will see how to toggle class of an element when a button's onClick event is called.

Here is the sample HTML

<button class="red btn" type="button" id="btn"  onclick="changeColor()">Click Me to toggle class</button>

and CSS

.btn{
  padding:20px 10px;
  color:white;
  border:none;
}

.red{
  background-color:red;
}

.green{
   background-color:green;
}

Then we will be using below Javascript code to toggle class on button click

function changeColor() {
     document.getElementById("btn").classList.toggle('red');
     document.getElementById("btn").classList.toggle('green');
}

In the above code, we are picking DOM elements based on it's id "btn" and then using classList.toggle, we are adding or removing classes based on if it's already there or not.

If class "red" exists, then it will be removed, if not, it will be added back to "btn"

You can take a look at the complete fiddle here

Toggle Class on Hover using Javascript

In the above sample, we were changing class based on button click, but we can also change class when user hover over the DOM element using Javascript events 'mouseenter' and 'mouseleave'

Considering we have above HTML and CSS, we can do some changes in our Javascript and it would result in below code

function changeColor() {
    this.classList.toggle('red');
    this.classList.toggle('green');
}

 document.querySelector('#btn').addEventListener('mouseenter', changeColor);
 document.querySelector('#btn').addEventListener('mouseleave', changeColor );

So here is the working fiddle demo for it

Replace all Existing Classes using Javascript

If you don't want to toggle classes using Javascript and want to replace one or more classes, then you can directly usine .className and provide all classes name using Javascript.

Here is the working code with comment's to explain it

 function changeColor() {
const btn = document.querySelector('#btn');

// print existing classes
console.log(btn.className); // 

// add new class
btn.className += 'btn';

// replace all existing classes
btn.className = 'red btn';
}

Since, there is alread .class reserved in Javascript as keyword, we are using .className to add or replace classes using it.

So complete fiddle demo considering we have below HTML and CSS

<button class="" type="button" id="btn"  onclick="changeColor()">Click Me to add class</button>

CSS

.btn{
  padding:20px 10px;
  color:white;
  border:none;
}

.red{
  background-color:red;
}

.green{
   background-color:green;
}

Fiddle: