How to Change the Class of an Element Using JavaScript

Answer: Use the classList Property

Modern browsers allow you to use the  classList  property of the DOM element to add, remove, or toggle CSS classes to HTML elements dynamically using JavaScript.

This example will demonstrate how to change the class and/or attributes of DIV elements on a click of a button. It works with all major browsers, including Chrome, Firefox and Microsoft Edge.

<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<title>Change an Element's Class with JavaScript</title>
        background: yellow;
        border: 5px solid #000;
        padding: 20px;
        display: none;
<div id="content">
    <h1>This is a heading</h1>
    <p>This is a paragraph of text.</p>

    <button type="button" onclick="addSingleClass()">Add Highlight Class</button>
    <button type="button" onclick="addMultipleClass()">Add Bordered and Padded Class</button>        
    <button type="button" onclick="removeSingleClass()">Remove Highlight Class</button>  
    <button type="button" onclick="removeMultipleClass()">Remove Bordered and Padded Class</button>
    <button type="button" onclick="toggleClass()">Toggle Hide Class</button>

// Selecting element
var elem = document.getElementById("content");

function addSingleClass(){
	elem.classList.add("highlight");  // Add a highlight class
function addMultipleClass(){
	elem.classList.add("bordered", "padded");  // Add bordered and padded class
function removeSingleClass(){
	elem.classList.remove("highlight");  // Remove highlight class
function removeMultipleClass(){
	elem.classList.remove("bordered", "padded");  // Remove bordered and padded class
function toggleClass(){
	elem.classList.toggle("hide");  // Toggle hide class

Alternately, the  className  property can be used to support older browsers. This property can be used to add or remove CSS classes.

<div id="info">Some important information!</div>
 // Selecting element
 var elem = document.getElementById("info");
 elem.className = "note";  // Add or replace all classes with note class
 elem.className += " highlight";  // Add a new class highlight
 elem.className += " bordered padded";  // Add two new classes bordered and padded
 elem.className = ""; // Remove all classes

To learn more about styling elements, please visit the JavaScript DOM Style tutorial.


Exit mobile version