You can toggle a class in vanilla JS by invoking the .toggle() method on an element's .classList property:

const paragraphs = document.querySelectorAll("p");

for (const paragraph of paragraphs) {

This is almost identical to the jQuery method that inspired it:

const $paragraphs = $("p");


The second argument

Like the jQuery method, the vanilla JS method accepts a second argument. This is a boolean value that determines whether the class should be added or removed:

paragraph.classList.toggle("highlight", addOrRemove);

This is equivalent to the following:

if (addOrRemove) {
} else {


Let's see this in action.

There's a demo in the jQuery documentation which we'll rewrite in vanilla JS. It adds the "highlight" class to the clicked paragraph on every third click, and removes the "highlight" class on every first and second click:

// I don't know why they've declared this variable; they're not using it
var count = 0;

$("p").each(function () {
var $thisParagraph = $(this);
var count = 0;

$ () {
$thisParagraph.find("span").text("clicks: " + count);
$thisParagraph.toggleClass("highlight", count % 3 === 0);

The jQuery version uses a closure to keep track of the count for each paragraph. I personally don't like this solution because it means adding a separate event listener to each paragraph.

It's better to use event delegation, meaning we only have to add one event listener. Instead of a closure, we'll use a WeakMap to keep track of the count for each button. We'll use buttons instead of paragraphs for better keyboard accessibility:

const app = document.querySelector("#app");

const clickCount = Array.from(app.children).reduce(
(count, button) => count.set(button, 0),
new WeakMap()

function handleClick(event) {
const button ="button");
if (button === null) return;

let count = clickCount.get(button);
if (count === undefined) return;

clickCount.set(button, ++count);

const [span] = button.children;
span.textContent = `clicks: ${count}`;

button.classList.toggle("highlight", count % 3 === 0);

app.addEventListener("click", handleClick);

Either way, this is the important line:

button.classList.toggle("highlight", count % 3 === 0);

Which is equivalent to the following:

if (count % 3 === 0) {
} else {

Note that the .toggleAttribute() method supports a second argument too!