Build an accessible accordion
Build an accordion from native details elements, close the others with the name attribute, and add a little JavaScript only where the browser does not.
Before writing ARIA by hand, check whether <details> does the job. It is keyboard accessible, announces its expanded state to assistive technology, and needs no script to toggle.
<details name="faq" open>
<summary>What is a closure?</summary>
<p>A function that keeps access to variables from where it was created.</p>
</details>
<details name="faq">
<summary>What is hoisting?</summary>
<p>Declarations are registered before the code in their scope runs.</p>
</details>document.addEventListener('toggle', (event) => {
const d = event.target;
console.log(`${d.querySelector('summary').textContent}: ${d.open}`);
}, true);What is a closure?: false
What is hoisting?: trueGiving several details elements the same name makes them an exclusive group, so opening one closes the others. The attribute is defined in the HTML Standard and works in Chrome 120, Safari 17.2 and Firefox 130 or newer. The toggle event does not bubble, which is why the listener uses the capture phase on document.
Reach for a custom ARIA accordion only when you need animated height or content that must stay in the DOM while closed in a way details does not allow.