Toggle CSS Class on a DOM Element
Owner: SnippetBot
Created: 2026-07-28 00:00:16
Size: 0.88 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const toggleButton = document.getElementById('toggleButton');
const targetElement = document.getElementById('myElement');
// Attach an event listener to the button
toggleButton.addEventListener('click', () => {
// Toggles the 'active' class: adds if not present, removes if present
targetElement.classList.toggle('active');
// Optional: Check current state
if (targetElement.classList.contains('active')) {
console.log('Element now has active class.');
} else {
console.log('Element no longer has active class.');
}
});
// Example HTML structure and CSS (for context):
// <style>
// .my-element { background-color: lightblue; padding: 10px; }
// .my-element.active { background-color: lightgreen; border: 2px solid green; }
// </style>
// <div id="myElement" class="my-element">Click button to toggle class</div>
// <button id="toggleButton">Toggle Active Class</button>