To toggle a class on an element in JavaScript, you can use the classList
property of the element. Here is an example of how to toggle a class on a button when it is clicked:
40 chars2 lines
index.tsx140 chars6 lines
In the above code, we first select the button element using document.getElementById()
. We then add an event listener to the button that listens for a click event. When the button is clicked, we call the toggle()
method on its classList
property, passing in the name of the class we want to toggle (active
in this case). This will add the class to the element if it doesn't already have it, or remove it if it does.
gistlibby LogSnag