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?
Student
I am Utpal Vishwas from Uttar Pradesh. Have completed my B. Tech. course from MNNIT campus Prayagraj in 2022. I have good knowledge of computer networking.
Sure, 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".