How to change style/class of an element using JavaScript ?
Last Updated :
01 May, 2023
In this article, we will learn how we can change the style/class of an element. If you want to build a cool website or app then UI plays an important role. We can change, add or remove any CSS property from an HTML element on the occurrence of any event with the help of JavaScript. There are two common approaches that allow us to achieve this task.
- style.property
- Changing the class itself
Approach 1: Changing CSS with the help of the style property:
Syntax:
document.getElementById("id").style.property = new_style
Example: In this example, we have built a PAN number validator. First, we will take the input value and match it with a regex pattern. If it matches then using JavaScript add an inline style on the <p> tag. Otherwise, add a different style on the <p> tag.
HTML
<!DOCTYPE html>
<html lang="en">
<body>
<h1 style="color: green;">
GeeksforGeeks
</h1>
<h2>
How can the style/class of
an element be changed?
</h2>
<b>Validate Pan Number</b>
<input type="text" id="pan" />
<p></p>
<button id="submit">Validate</button>
<script>
const btn = document.getElementById("submit");
btn.addEventListener("click", function () {
const pan = document.getElementById("pan").value;
const para = document.querySelector("p");
let regex = /([A-Z]){5}([0-9]){4}([A-Z]){1}$/;
if (regex.test(pan.toUpperCase())) {
para.innerHTML = "Hurrey It's correct";
// Inline style
para.style.color = "green";
} else {
para.innerHTML = "OOps It's wrong!";
// Inline style
para.style.color = "red";
}
});
</script>
</body>
</html>
Output:

Approach 2: Changing the class itself - We can use two properties that can be used to manipulate the classes.
The classList Property: The classList is a read-only property that returns the CSS class names of an element as a DOMTokenList object.
Syntax:
document.getElementById("id").classList
You can use the below-mentioned methods to add classes, remove classes, and toggle between different classes respectively.
- The add() method: It adds one or more classes.
- The remove() method: It removes one or more classes.
- The toggle() method: If the class does not exist it adds it and returns true. It removes the class and returns false. The second boolean argument forces the class to be added or removed.
Example: In this example, we are using the above-explained approach.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.hide {
display: none;
}
.blueColor {
color: blue;
}
</style>
</head>
<body>
<h1 style="color: green;">
GeeksforGeeks
</h1>
<h2>
How can the style/class of
an element be changed?
</h2>
<h3>Hide and Show the Para</h3>
<p>
GeeksforGeeks is a computer science portal
for geeks. This platform has been designed
for every geek wishing to expand their
knowledge, share their knowledge, and is
ready to grab their dream job. GFG have
millions of articles, live as well
as online courses, thousands of tutorials
and much more just for the geek inside you.
</p>
<button id="hide">Hide</button>
<button id="show">Show</button>
<button id="color">Change Color</button>
<script>
const btn_hide = document.getElementById("hide");
const btn_show = document.getElementById("show");
const btn_color = document.getElementById("color");
const para = document.querySelector("p");
btn_hide.addEventListener("click", function () {
para.classList.add("hide");
});
btn_show.addEventListener("click", function () {
para.classList.remove("hide");
});
btn_color.addEventListener("click", function () {
para.classList.toggle("blueColor");
});
</script>
</body>
</html>
Output:

In the above example, we define two manipulation classes "hide" and "toggleColor" which hide an element and change color to blue respectively. When the Hide button is clicked, the hide class is added to the "p" tag which hides it. When the Show button is clicked, it removes the present hide class from the "p" tag. When the Change Color button is clicked once it adds "toggleColor" class to the p tag(which makes the text color blue) and when clicked again it removes the toggleColor class.
The className Property: This property is used to set the current class of the element to the specified class.
Syntax:
document.getElementById("id").className = class
Example: In this example, we are using the className property to change the color of the element.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.colorBlue {
color: blue;
}
.colorRed {
color: red;
}
</style>
</head>
<body>
<h1 style="color: green;">
GeeksforGeeks
</h1>
<h2>
How can the style/class of
an element be changed?
</h2>
<h3>className Example</h3>
<p class="colorBlue">
GeeksforGeeks is a computer science portal
for geeks.This platform has been designed
for every geek wishing to expand their
knowledge, share their knowledge and is
ready to grab their dream job. GFG have
millions of articles, live as well
as online courses, thousands of tutorials
and much more just for the geek inside you.
</p>
<button id="submit">Change Color</button>
<script>
const btn = document.getElementById("submit");
const para = document.querySelector("p");
btn.addEventListener("click", function () {
para.className = "colorRed";
});
</script>
</body>
</html>
Output:
In the above example, the existing ColorBlue class is set to the colorRed class using the className property which changes font color from blue to red.
Similar Reads
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial
JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. JavaScript is an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side : On client sid
11 min read
Web Development
Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Class Diagram | Unified Modeling Language (UML)
A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Spring Boot Tutorial
Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers
React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
HTML Tutorial
HTML stands for HyperText Markup Language. It is the standard language used to create and structure content on the web. It tells the web browser how to display text, links, images, and other forms of multimedia on a webpage. HTML sets up the basic structure of a website, and then CSS and JavaScript
10 min read
JavaScript Interview Questions and Answers
JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
Backpropagation in Neural Network
Backpropagation is also known as "Backward Propagation of Errors" and it is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network. In this article we will explore what
10 min read
Polymorphism in Java
Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read