如何为按钮列表添加active类?求点击激活的JavaScript代码
Got it, here's a couple of solid solutions to handle adding the active class to your filter buttons when clicked—ensuring only one button is active at any time:
Vanilla JavaScript (No Libraries Needed)
This approach uses plain JavaScript, so you don't need to rely on jQuery or other frameworks:
// Grab all filter button elements const filterButtons = document.querySelectorAll('.filter-button'); // Attach click event to each button filterButtons.forEach(button => { button.addEventListener('click', () => { // First, remove the active class from every button filterButtons.forEach(btn => btn.classList.remove('active')); // Then add the active class to the button that was clicked button.classList.add('active'); }); });
Quick Notes:
- Don't forget to add the
activeclass to your default button (like the "All" button) in your HTML so it's active when the page loads:<button class="filter-button btn active" data-filter="all"><span class="caps">A</span>ll</button> - Make sure this script runs after the DOM is loaded—you can either put it at the end of your
<body>tag, or wrap it in aDOMContentLoadedevent listener.
jQuery Alternative (If You're Using jQuery)
If your project already uses jQuery, this shorter version works great:
// When any filter button is clicked $('.filter-button').click(function() { // Remove active class from all filter buttons $('.filter-button').removeClass('active'); // Add active class to the clicked button $(this).addClass('active'); });
Either solution will handle the active state switching smoothly for your button group.
内容的提问来源于stack exchange,提问作者teshu katepalli
相关产品推荐
相关产品推荐

