Coding Triumph

Helpful code snippets & tutorials

How to toggle an HTML class with vanilla JavaScript (no jQuery)

Toggling an HTML class has become simple with modern JavaScript, all you need is the DOMTokenList.toggle() method which is supported by all modern browsers so no need for JQuery.

First, we need a button:

<button onclick="toggleClass()">Toggle</button>
<p>Click "Toggle" to toggle "myClass" on and off.</p>

<div id="myId">
    <p>I am paragraph.</p>
</div>

And a click callback:

function toggleClass() {
  document.querySelector("#myId").classList.toggle("myClass");
}

That’s it. Every time you click the button, the class myClass will be added or removed from the div.

If you like this post, please share
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments