How to Toggle Class in JavaScript: Simple Guide
Use the
element.classList.toggle('className') method to add the class if it is missing or remove it if it is present. This method is simple and works directly on the element's class list.Syntax
The toggle method is called on an element's classList property. It takes one required argument, the class name as a string, and an optional second boolean argument to force add or remove.
element: The HTML element you want to change.classList: A property that holds all classes of the element.toggle('className'): Adds the class if missing, removes if present.toggle('className', force): Ifforceis true, adds the class; if false, removes it.
javascript
element.classList.toggle('className'); // With force argument // element.classList.toggle('className', true); // always adds // element.classList.toggle('className', false); // always removes
Example
This example shows a button that toggles the highlight class on a paragraph when clicked. The class changes the paragraph's background color.
javascript
const button = document.createElement('button'); button.textContent = 'Toggle Highlight'; const paragraph = document.createElement('p'); paragraph.textContent = 'Click the button to toggle highlight class.'; // Define CSS style for highlight const style = document.createElement('style'); style.textContent = '.highlight { background-color: yellow; }'; document.head.appendChild(style); document.body.appendChild(paragraph); document.body.appendChild(button); button.addEventListener('click', () => { paragraph.classList.toggle('highlight'); });
Output
A webpage with a paragraph and a button. Clicking the button toggles a yellow background on the paragraph.
Common Pitfalls
Common mistakes include:
- Trying to toggle class on
nullor undefined elements (make sure the element exists). - Using
classNamestring manipulation instead ofclassList, which is error-prone. - Forgetting that
togglereturnstrueif the class was added,falseif removed.
javascript
/* Wrong way: manipulating className string directly */ const el = document.querySelector('#myElement'); el.className = el.className.includes('active') ? el.className.replace('active', '') : el.className + ' active'; /* Right way: use classList.toggle */ el.classList.toggle('active');
Quick Reference
| Method | Description |
|---|---|
| element.classList.toggle('className') | Adds class if missing, removes if present |
| element.classList.toggle('className', true) | Always adds the class |
| element.classList.toggle('className', false) | Always removes the class |
Key Takeaways
Use element.classList.toggle('className') to switch a class on or off easily.
Always ensure the element exists before toggling its class to avoid errors.
Avoid manipulating class strings manually; use classList methods for safety.
The toggle method returns true if the class was added, false if removed.
You can force add or remove a class by passing a second boolean argument.