<div class="tabs_wrap">
<div class="tabs_container">
<button class="btn tab tab--1 tab--active" data-tab="1">
tab button 1
</button>
<button class="btn tab tab--2 tab--active" data-tab="2">
tab button 2
</button>
</div>
<div class="content content--1 content--active">
<div>
contents 1
</div>
</div>
<div class="content content--2 content--active">
<div>
contents 2
</div>
</div>
</div>
const tabs = document.querySelectorAll('.tab');
const tabsContainer = document.querySelector('.tabs_container');
const tabsContent = document.querySelectorAll('.content');
tabsContainer.addEventListener('click', function (e) {
const clicked = e.target.closest('.tab');
// Guard clause
if (!clicked) return;
// Remove active classes
tabs.forEach(t => t.classList.remove('tab--active'));
tabsContent.forEach(c => c.classList.remove('content--active'));
// Activate tab
clicked.classList.add('tab--active');
// Activate content area
document.querySelector(`.content-${clicked.dataset.tab}`).classList.add('content--active');
});
Avoid using forEach
to attach events to each tab. Instead, leverage event bubbling to set an event listener on the parent element and determine which child element it corresponds to.
Top comments (0)