how to toggle a class on an element in javascript

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:

<button id="myButton">Click me</button>
40 chars
2 lines
index.tsx
const button = document.getElementById('myButton');

button.addEventListener('click', function() {
  button.classList.toggle('active');
});
140 chars
6 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