element.classList.toggle(className)
element.classList.toggle(className, force)
<style>
    .bold {
        font-weight: 600;
    }
    .bg-red {
        background-color: red;
    }
</style>
<p class="bold">The background color is added or removed.</p>
<button type="button">Add/Remove Background Color</button>
const elem = document.querySelector("p");
const button = document.querySelector("button");

button.addEventListener("click", () => { // Button click event
    // Adds the "bg-red" class value if it does not exist; otherwise removes it
    elem.classList.toggle("bg-red");
});
Rendered Output Click the "Add/Remove Background Color" button!
<style>
    .bg-red {
        background-color: red;
    }
</style>
<input type="text">
<button type="button">Add/Remove Background Color</button>
<p style="color: red;">
    The status of the "bg-red" class value will be displayed here.
</p>
const inputElem = document.querySelector("input");
const button = document.querySelector("button");
const msgElem = document.querySelector("p");

button.addEventListener("click", () => { // Button click event
    if (inputElem.classList.toggle("bg-red")) { // If the "bg-red" class value is added
        msgElem.textContent = 'The "bg-red" class value has been added.';
    } else { // If the "bg-red" class value is removed
        msgElem.textContent = 'The "bg-red" class value has been removed.';
    }
});
Rendered Output Click the "Add/Remove Background Color" button!
<style>
    .bg-red {
        background-color: red;
    }
</style>
<ol>
    <li>List Item</li>
    <li>List Item</li>
    <li>List Item</li>
    <li>List Item</li>
    <li>List Item</li>
</ol>
<button type="button">Add Background Color to Even Items</button>
const items = document.querySelectorAll("li");
const button = document.querySelector("button");
const itemsLength = items.length;

button.addEventListener("click", () => { // Button click event
    for (let i = 0; i < itemsLength; i++) {
        items[i].classList.toggle("bg-red", i % 2 === 1);
        /*  i % 2 === 1
            : Evaluates to true for even-numbered list items and false for odd-numbered list items
            : The "bg-red" class value is forcibly added to even-numbered list items
        */
    }
});
Rendered Output Click the "Add Background Color to Even Items" button!