Sure, here is how to change an element's class with JavaScript:
JavaScript
// 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
<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".
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
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".