How to change a class property of DOM element in JavaScript?

Are you wondering how to change the CSS class property of a DOM element in JavaScript?

Look no further! Our comprehensive tutorial will guide you through the whole process of selecting elements and modifying their class property using the className and classList properties.

This article will provide clear explanations and practical examples so that you’ll be able to master this essential skill in no time.

Don’t miss out on this opportunity to enhance your JavaScript knowledge and skills!

What is DOM Element?

In order to effectively modify the class property of a DOM element using JavaScript, it’s important to understand how the DOM works.

The DOM is like a map that shows the structure of an HTML or XML document. It allows you to find, move around, and modify different parts of the document.

DOM Elements

To change the class property of a DOM element in JavaScript, you first need to select the element(s) you want to change. JavaScript provides several methods for selecting DOM elements based on different criteria.

Here are the most common methods:

📌 getElementById: This method allows you to select an element by its unique ID.

📌 getElementsByClassName: With this method, you can select elements based on their class name.

📌 getElementsByTagName: This method lets you select elements based on their tag name.

📌 querySelector: By using a specific CSS selector, you can select the first element that matches the selector.

📌 querySelectorAll: This method selects all elements that match the specified CSS selector.

By using these selection methods, you can easily choose the elements you want to modify the class property of.

How to change class property of a DOM element in JavaScript?

To change the class property of a DOM element in JavaScript, as what we mentioned earlier you can use the className property or the classList property.

Syntax:

Get the class name of an element by using the className property:

HTMLElementObject.className

Change the class name of an element by setting the value of the className property:

HTMLElementObject.className = class

Here are a few methods you can use:

1. Use the className property

You can change all the class names of a DOM element at once by using the className property.

For instance, if you want to change the class attribute of an element with the ID “MyElement” to “MyClass.”

You can use the following code:

document.getElementById("MyElement").className = "MyClass";

Here’s an example of complete code:

<!DOCTYPE html>
<html lang="en">
<body>
	<h1 style="color: Blue;">
		Itsourcecode
	</h1>

	<h2>
		How to change class property of a DOM element in JavaScript?
	</h2>

	<b>Validate Facebook Code:</b>

	<input type="text" id="code" />
	<p></p>
	<button id="submit">Sumbit</button>

	<script>
		const btn = document.getElementById("submit");
		btn.addEventListener("click", function () {
			const code = document.getElementById("code").value;
			const para = document.querySelector("p");

			let regex = /^[0-9]{6}$/;
			if (regex.test(code)) {
				para.innerHTML = "The code you provide is Correct!";

				// Inline style
				para.style.color = "green";
			} else {
				para.innerHTML = "The code you provide is Incorrect!";

				// Inline style
				para.style.color = "red";
			}
		});
	</script>
</body>
</html>

Output:

2. Use the classList property

The classList property offers a variety of methods to easily add, remove, and toggle class values for an element.

Here are a few examples:

  1. It adds one or more class values.

element.classList.add('active');

  1. Removes one or more class values.
element.classList.remove('active');

  1. Toggles a class on or off.
element.classList.toggle('active');

  1. Checks if a class value exists.
element.classList.contains('active');

  1. Replaces an existing class value with a new class value.
element.classList.replace('oldClass', 'newClass');

Here’s an example of complete code:

<!DOCTYPE html>
<html lang="en">

<head>
	<style>
		.hide {
			display: none;
		}

		.pinkColor {
			color: pink;
		}
		
		body {
			display: flex;
			flex-direction: column;
			align-items: center;
			text-align: center;
		}
		
		button {
			margin: 5px;
		}
	</style>
</head>

<body>
	<h1 style="color: blue;">
		Welcome to Itsourcode!
	</h1>
	
	<h2>
			How to change class property of a DOM element in JavaScript?

	</h2>
	
	<h3>Example code using classList property</h3>
	
	<p>
		Welcome to Itsourcecode.com – your go-to destination for free projects with source code and tutorials.

Every programming problem has a solution, and is committed to providing just that.

As technology becomes integral to our lives, the IT industry is growing exponentially.


Itsourcecode.com is designed to help new and experienced programmers expand their knowledge and improve their programming skills.

At Itsourcecode.com, we are committed to providing the best project with source code, resources, Online compilers, and Tutorials to support your programming journey.

We understand that learning is a continuous process, and we encourage you to keep reading and learning from our articles.

With Itsourcecode.com, you can rest assured that your source code is no longer a problem.

Thank you for choosing Itsourcecode.com as your partner in your programming journey.

Our team looks forward to being a part of your success.
	</p>
	
	<button id="hide">Hide</button>
	<button id="show">Show</button>
	<button id="color">Click the button to 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("pinkColor");
		});
	</script>
</body>

</html>

Output:

How to change CSS class property of a DOM element in JavaScript?

You can change the CSS class of a DOM element using the classList property in JavaScript.

As we mentioned above, the classList property allows you to access the list of classes for an element and provides methods like add(), remove(), and toggle() to modify the classes.

For example, here’s how you can add a class to an element:

let element = document.getElementById('id1');
element.classList.add('newClass');


You can also remove a class from an element using the remove() method:

element.classList.remove('newClass');

And you can toggle a class using the toggle() method:

element.classList.toggle('newClass');

These methods make it easy to change the classes of an element without directly modifying the className property.

How to change class attribute in JavaScript?

You have the ability to change the class attribute of a DOM element by directly changing its className property in JavaScript.

The className property allows you to set or retrieve the value of the class attribute of an element.

Here’s an example that demonstrates how to change the class attribute of an element using JavaScript:

let element = document.getElementById('id1');
element.className = "newClass";

By using this code, you can assign the class attribute of the element with the ID “id1” to the value “newClass”.

Additionally, if you want to add multiple classes, you can simply separate them with spaces.

element.className = "class1 class2 class3";

By using this code, you can assign multiple classes to the element. In this example, the element will have three classes applied to it: “class1,” “class2,” and “class3.”

Conclusion

In conclusion, this article provides a comprehensive tutorial on how to change the CSS class property of a DOM element in JavaScript.

It explains the concept of DOM elements and different methods for selecting elements. The article also covers two approaches to changing the class property: using the className property and the classList property.

This article also provides example codes to demonstrate the process. We are hoping that this article provides you with enough information that helps you understand the JavaScript change class.

You can also check out the following article:

Thank you for reading itsourcecoders 😊.


Frequently Asked Questions

Is JavaScript still worth learning in 2026?
Yes. JavaScript runs on 98% of websites for the front-end, dominates the back-end via Node.js, powers mobile apps through React Native, builds desktop tools through Electron, and is the scripting layer for most AI tooling (LangChain.js, OpenAI SDK, Vercel AI). Whether you target web, mobile, AI, or full-stack capstones, JavaScript is the broadest single language you can learn.
What is the difference between var, let, and const?
var is function-scoped, hoisted to the top of its scope, and can be redeclared, which leads to bugs in modern code. let is block-scoped (only visible inside the nearest {}) and can be reassigned. const is block-scoped and cannot be reassigned, although object contents can still mutate. Default to const for everything, switch to let only when you actually need to reassign, and avoid var in any code written after 2017.
Which JavaScript version should I target in 2026?
Target ES2020 (ES11) as the safe baseline because every modern browser and Node.js 14+ supports it fully. ES2022 adds useful features like top-level await, private class fields with the # prefix, and the .at() array method. If you are writing for older browsers (IE11 or older Android WebViews), transpile down with Babel or use a build tool like Vite, esbuild, or webpack.
What is the best free editor for JavaScript?
Visual Studio Code is the industry standard, free, with built-in IntelliSense, debugger, terminal, Git, and a huge extension marketplace (ESLint, Prettier, GitHub Copilot, Tailwind). Install the JavaScript and TypeScript Nightly extension for the latest language features. JetBrains WebStorm is more powerful and free for students with a verified .edu email. For quick scratchpad work, the Chrome DevTools Sources panel includes a workspace and breakpoint debugger.
How do I run JavaScript locally vs in the browser?
In the browser: open DevTools with F12 (or right-click then Inspect), go to the Console tab, type or paste your code, press Enter. For HTML pages, add a script tag pointing to your .js file. Locally with Node.js: download Node from nodejs.org (LTS version), then run node script.js in your terminal from the file folder. Use the same Node setup for backend capstones, API integrations, and scripts that do not need a browser.
What can I build with JavaScript for my BSIT capstone?
Common BSIT capstones in JavaScript: full-stack web apps using React or Vue on the front-end with Node.js and Express on the back-end (MongoDB or MySQL for the database), real-time chat or notification systems using Socket.io, single-page dashboards with Chart.js or D3.js, cross-platform mobile apps with React Native, AI-powered chatbots using OpenAI SDK and LangChain.js, and Chrome extensions for productivity tools. Add Tailwind CSS for the UI and Vercel or Netlify for free deployment.
Caren Bautista

Technical Writer at PIES IT Solution

Responsible for crafting clear, well-structured, and beginner-friendly content across the platform. Handles the writing, proofreading, and editorial review of tutorials, guides, and documentation to ensure every article is accurate, readable, and easy to follow.

Expertise: Technical Writing · Content Creation · Documentation · Editorial Writing · JavaScript · TypeScript · Python · Python Errors · HTTP Errors · MS Excel  · View all posts by Caren Bautista →

Leave a Comment