How can I change an element's class with JavaScript, please provide sample?
How can I change an element's class with JavaScript, please provide sample?
19431-Jul-2023
Updated on 01-Aug-2023
Home / DeveloperSection / Forums / How can I change an element's class with JavaScript, please provide sample?
How can I change an element's class with JavaScript, please provide sample?
Aryan Kumar
01-Aug-2023Sure, here is how to change an element's class with JavaScript:
JavaScript
The
element
variable will contain a reference to the element whose class you want to change. TheclassList
property of theelement
variable will contain an array of the element's current classes. Theadd()
method of theclassList
property will add a new class to the element. Theremove()
method of theclassList
property will remove a class from the element.Here is an example of how to use this code:
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".