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?
371
31-Jul-2023
Updated on 01-Aug-2023
Aryan Kumar
01-Aug-2023Sure, here is how to change an element's class with JavaScript:
JavaScript
The
elementvariable will contain a reference to the element whose class you want to change. TheclassListproperty of theelementvariable will contain an array of the element's current classes. Theadd()method of theclassListproperty will add a new class to the element. Theremove()method of theclassListproperty 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".