An accordion is a stack of sections where only one is open at a time — the classic FAQ layout. It is the tabs component's vertical cousin, and it teaches you the same core skill: managing which one thing is active.
What you are building
A FAQ accordion. Click a question, its answer opens. Click another question, the first one closes.
The HTML: a button and a panel per item
<div class="accordion">
<div class="item">
<button class="accordion-btn">What is JavaScript?</button>
<div class="accordion-panel">JavaScript is the programming language of the web.</div>
</div>
<div class="item">
<button class="accordion-btn">Do I need a framework?</button>
<div class="accordion-panel">No. Learn the language first, then pick a framework.</div>
</div>
</div>
The JavaScript: toggle, and close the others
const buttons = document.querySelectorAll('.accordion-btn');
buttons.forEach((btn) => {
btn.addEventListener('click', () => {
const panel = btn.nextElementSibling;
const isOpen = !panel.classList.contains('hidden');
// Close everything first
document.querySelectorAll('.accordion-panel').forEach((p) => p.classList.add('hidden'));
// Then open this one — unless it was already open
if (!isOpen) panel.classList.remove('hidden');
});
});
The if (!isOpen) check is what lets users close the open item by clicking it again. Without it, clicking the open question would close it and immediately reopen it.
The CSS: a smooth open animation
.hidden { display: none; }
.accordion-panel {
padding: 12px;
border-bottom: 1px solid #ddd;
}
.accordion-btn {
width: 100%;
text-align: left;
padding: 12px;
font-weight: bold;
cursor: pointer;
}
For a smooth height animation, animate max-height instead of toggling display — but the toggle version above is the correct starting point, and most production accordions still use it.
The one thing to remember
nextElementSibling is the link between the button and its panel. It works because the panel directly follows the button in the HTML. If you ever restructure the markup, that link breaks — so keep the button and panel as siblings, or switch to a data- attribute link like the tabs component uses.
Top comments (0)