How do Add class using Javascript?

I wanted to add or remove classes from my HTML <div> dynamically using Javascript, I don't want to use jQuery here, so How can I add a class using JS?

If possible, I would also like to know how can I toggle class in Javascript

Asked by:- neena
: 2349 At:- 9/26/2018 11:17:25 AM
Javascript js-add-class javascript-toggle-class

1 Answers
profileImage Answered by:- manish

Suppose this is your HTML and you want to add a class using javascript

<div id="MainDiv" class="ClassForDiv">

So here is the Javascript for it to add class for <div id="div1">

Add Class using Javascript

var nameElem = document.getElementById("MainDiv");

Toggle Class using Javascript

Every element has a classList property containing its class attributes. This property provides methods that make it straightforward to add or remove a class.

function toggleClass() {

 var myDivClasses = document.getElementById("MainDiv").classList;

 if (myDivClasses.contains("blue")) {
 }else {


An even simpler way to accomplish the same thing is to use the toggle() method. Which will add the provided class if it is not present, or remove it if it is:

function toggleColor() {



here is the complete Javascript example to toggle class using JS

Removing class using Javascript

You can use classList.remove() method to remove a class


Creating Global function to add/ remove class using Javascript

You can also create Global function like this

function addClass( classname, element ) {
    var cn = element.className;
    //test for existance
    if( cn.indexOf( classname ) != -1 ) {
    //add a space if the element already has class
    if( cn != '' ) {
        classname = ' '+classname;
    element.className = cn+classname;

function removeClass( classname, element ) {
    var cn = element.className;
    var rxp = new RegExp( "\\s?\\b"+classname+"\\b", "g" );
    cn = cn.replace( rxp, '' );
    element.className = cn;

so, basically it will help your to reuse same code again and again.

Hope it helps.

At:- 9/26/2018 4:17:39 PM Updated at:- 9/27/2022 7:39:08 AM
Excellent answer, thank you for complete details. 0
By : neena - at :- 10/2/2018 8:17:24 AM

Login/Register to answer
Register directly by posting answer/details

Full Name *

Email *

By posting your answer you agree on privacy policy & terms of use