To change an element’s class with JavaScript, you can use the “className” attribute. The document.getElementById() method is used to return the element in the document with the “id” attribute, and the “className” attribute can be used to change/append the class of the element.
Syntax
document.getElementById("myElement").className = "myclass";
Example 1: Changing an element’s class
We will change the class name on the button click.
<!DOCTYPE html>
<html>
<head>
<title>Change Class Name</title>
<style>
.oldClass {
color: blue;
}
.newClass {
color: red;
}
</style>
</head>
<body>
<p id="myElement" class="oldClass">Hello, World!</p>
<button onclick="changeClass()">Change Class</button>
<script>
function changeClass() {
var element = document.getElementById("myElement");
element.className = "newClass";
}
</script>
</body>
</html>
Before changing the class name
After changing the class name
Example 2: Toggle between two class names
<!DOCTYPE html>
<html>
<head>
<title>Toggle Class Name</title>
<style>
.class1 {
color: blue;
}
.class2 {
color: red;
}
</style>
</head>
<body>
<p id="myElement" class="class1">Hello, World!</p>
<button onclick="toggleClass()">Toggle Class</button>
<script>
function toggleClass() {
var element = document.getElementById("myElement");
if (element.className === "class1") {
element.className = "class2";
} else {
element.className = "class1";
}
}
</script>
</body>
</html>
Toggle the first time
Toggle the second time
That’s it.

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.