How to Change the Class of an Element Using JavaScript

Topic: JavaScript / jQueryPrev|Next

Answer: Use the classList Property

In modern browsers you can use the DOM element's classList property to add, remove or toggle CSS classes to the HTML elements dynamically with JavaScript.

The following example will show you how to change the class of a DIV element onclick of the button. It works all major browsers such as Chrome, Firefox, Microsoft Edge, Safari, etc.

<!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

Alternatively, to support older browsers you can use the className property. The following example demonstrates how to add or replace CSS classes using this property.

<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

Please check out the tutorial on JavaScript DOM Styling to learn more about element's styling.

Related FAQ

Here are some more FAQ related to this topic:

Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties