Ask any question about JavaScript here... and get an instant response.
How do I toggle a CSS class on multiple elements when clicking a button using JavaScript event listeners?
Asked on Nov 22, 2025
Answer
To toggle a CSS class on multiple elements when a button is clicked, you can use JavaScript event listeners to add or remove the class from each element. Below is a simple example demonstrating this functionality.
<!-- BEGIN COPY / PASTE -->
<button id="toggleButton">Toggle Class</button>
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item">Item 3</div>
<style>
.highlight {
background-color: yellow;
}
</style>
<script>
document.getElementById('toggleButton').addEventListener('click', function() {
const items = document.querySelectorAll('.item');
items.forEach(item => {
item.classList.toggle('highlight');
});
});
</script>
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- The "toggleButton" button is used to trigger the event listener.
- "querySelectorAll" selects all elements with the class "item".
- "forEach" iterates over each selected element.
- "classList.toggle" adds the "highlight" class if it's not present, or removes it if it is.
- The "highlight" class is defined in the style block to change the background color.
Recommended Links:
