---
title: "How can I change an element's class with JavaScript, please provide sample?"  
description: "How can I change an element's class with JavaScript, please provide sample?"  
author: "Utpal Vishwas"  
published: 2023-07-31  
updated: 2023-08-01  
canonical: https://www.mindstick.com/forum/159382/how-can-i-change-an-element-s-class-with-javascript-please-provide-sample  
category: "javascript"  
tags: ["javascript", "class", "html element"]  
reading_time: 2 minutes  

---

# How can I change an element's class with JavaScript, please provide sample?

How can I change an element's [class](https://www.mindstick.com/blog/165/generic-class-in-c-sharp) with [JavaScript](https://www.mindstick.com/articles/874/how-to-create-watermark-text-for-textbox-by-using-javascript), [please provide sample](https://www.mindstick.com/forum/159390/how-do-i-vertically-align-text-in-a-div-please-provide-sample)?

## Replies

### Reply by Aryan Kumar

Sure, here is how to change an element's class with JavaScript:

JavaScript

```plaintext
// Get the element
var element = document.getElementById("myElement");

// Get the current classes
var currentClasses = element.classList;

// Add the new class
currentClasses.add("new-class");

// Remove the old class
currentClasses.remove("old-class");
```

The `element` variable will contain a reference to the element whose class you want to change. The `classList` property of the `element` variable will contain an array of the element's current classes. The `add()` method of the `classList` property will add a new class to the element. The `remove()` method of the `classList` property will remove a class from the element.

Here is an example of how to use this code:

HTML

```plaintext
<html>
<body>

<div id="myElement" class="my-class">This is my element</div>

<script>
// Get the element
var element = document.getElementById("myElement");

// Get the current classes
var currentClasses = element.classList;

// Add the new class
currentClasses.add("new-class");

// Remove the old class
currentClasses.remove("my-class");
</script>

</body>
</html>
```

This code will create a div element with the class "my-class". The `console.log()` method will print the element's current classes to the console. After the code is executed, the element will have the class "new-class" and will no longer have the class "my-class".


---

Original Source: https://www.mindstick.com/forum/159382/how-can-i-change-an-element-s-class-with-javascript-please-provide-sample

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
