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>

And a click callback:

function toggleClass() {

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
Notify of
Inline Feedbacks
View all comments