How to add or remove CSS classes from an HTML element using JavaScript?

To add or remove CSS classes from an HTML element using JavaScript, you can use the classList property. The classList property provides methods to add, remove, toggle, or check for the presence of CSS classes on an element.

To add a CSS class to an element, you can use the add() method:

var element = document.getElementById("myElement"); element.classList.add("myClass");

To remove a CSS class from an element, you can use the remove() method:

var element = document.getElementById("myElement"); element.classList.remove("myClass");

To toggle a CSS class on an element (add it if it's not there and remove it if it's already present), you can use the toggle() method:

var element = document.getElementById("myElement"); element.classList.toggle("myClass");

To check if an element has a specific CSS class, you can use the contains() method:

var element = document.getElementById("myElement"); if (element.classList.contains("myClass")) { // do something if the class is present } else { // do something if the class is not present }

These methods can be used to dynamically manipulate CSS classes on HTML elements using JavaScript.