How To Change Class Name of an HTML Element in Javascript?

This article will guide you on how you can change or replace the existing class name of an HTML element with the help of JS (Javascript). There is a property in Javascript to replace the existing class value or to add the class on the Html tag, which is className.

If the element has not a class previously, then it will be added otherwise will be replaced.

Step 1: First of all, give an id value to the element, of which you want to change the value of the class.

Step 2: Use any Javascript selector like id selector or other selectors to select the element in Javascript. If you have not set id value in the HTML element, then you can select it also by using the tag selector.

Step 3: Now, apply className property on the variable (That has selected the HTML tag). And give your desirous class value.

See below Example

<!DOCTYPE html>
	<title>How to change class of an HTML element in Javascript?</title>
	<link rel="stylesheet" href="">
<h1 align="center"><i class="fa fa-home" id="icon"></i></h1><br />

<center><button id="change-class">Change Class</button></center>

	var change_class=document.getElementById("change-class");
		var icon=document.getElementById("icon");
		icon.className="fa fa-gear";

Leave a Comment