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

Date Published: 20/03/2020 Published By: JaiSchool

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>
<html>
<head>
	<title>How to change class of an HTML element in Javascript?</title>
	<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<h1 align="center"><i class="fa fa-home" id="icon"></i></h1><br />

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

<script>
	var change_class=document.getElementById("change-class");
	change_class.onclick=function()
	{
		var icon=document.getElementById("icon");
		icon.className="fa fa-gear";
	}
	
</script>
</body>
</html>

Publish A Comment

Leave a Reply

Your email address will not be published. Required fields are marked *