Episode 17 of 18
Tabbed Content
Build a tabbed content component from scratch — switch between content panels by clicking tab buttons using the DOM.
Tabbed Content
Tabs are a common UI pattern — clicking a tab header shows its associated content panel and hides the others. You will build this from scratch using DOM manipulation and events.
The HTML
<div class="tabs">
<ul class="tab-headers">
<li class="tab-header active" data-target="panel-1">Tab 1</li>
<li class="tab-header" data-target="panel-2">Tab 2</li>
<li class="tab-header" data-target="panel-3">Tab 3</li>
</ul>
<div class="tab-content">
<div id="panel-1" class="panel active">Content for Tab 1</div>
<div id="panel-2" class="panel">Content for Tab 2</div>
<div id="panel-3" class="panel">Content for Tab 3</div>
</div>
</div>
The CSS
.panel { display: none; padding: 20px; background: #f9f9f9; }
.panel.active { display: block; }
.tab-header { cursor: pointer; padding: 10px 20px; display: inline-block; }
.tab-header.active { border-bottom: 3px solid #42b883; font-weight: bold; }
The JavaScript
var headers = document.querySelectorAll('.tab-header');
var panels = document.querySelectorAll('.panel');
headers.forEach(function(header) {
header.addEventListener('click', function() {
// Remove active from all headers and panels
headers.forEach(function(h) { h.classList.remove('active'); });
panels.forEach(function(p) { p.classList.remove('active'); });
// Add active to clicked header
this.classList.add('active');
// Show the matching panel
var target = this.dataset.target;
document.getElementById(target).classList.add('active');
});
});
How It Works
User clicks "Tab 2"
↓
Remove .active from all headers and panels
↓
Add .active to "Tab 2" header
↓
Read data-target="panel-2"
↓
Add .active to #panel-2 → CSS shows it
Key Takeaways
- Use
data-targetattributes to link tab headers to content panels - Toggle the
activeclass — CSS controls visibility withdisplay: none/block - Remove active from all, then add to the clicked one — the "remove all, add one" pattern
- This pattern works for tabs, accordions, carousels, and any toggle-based UI