Sub topic 8
Exclusive Accordions with the name Attribute
A set of details elements can behave as an accordion, where opening one panel closes the others, using a single attribute and no script. This chapter covers how the grouping works, how it interacts with the open attribute, the open property and the toggle event, and where it breaks down.
This chapter assumes you have read the earlier chapters of this tutorial or know the following:
- How
detailsandsummaryform a disclosure widget. - How the
openattribute sets the initial state. - How to listen for the
toggleevent. - Basic CSS selectors such as
details[open].
What "exclusive" means
A plain details element is independent. Opening one has no effect on any other. An accordion is different, because the panels are linked and at most one is expanded at a time. Before the name attribute existed, developers built this with JavaScript. A click handler on each panel would close its siblings.
The name attribute moves that rule into the browser. Every details element with the same name value belongs to one group. When one member opens, the browser closes any other open member of that group.
<details name="faq">
<summary>How do I reset my password?</summary>
<p>Use the reset link on the sign-in page.</p>
</details>
<details name="faq">
<summary>How do I change my email?</summary>
<p>Open account settings and edit the email field.</p>
</details>Opening the second item closes the first. No listener, state variable or class toggling is involved.
The name attribute on details has nothing to do with the name attribute on form controls. It does not submit anything. It only labels the group, much like the name on a set of radio buttons. The comparison with radio buttons is useful, with one difference noted below.
A complete working page
This page contains one accordion with three panels. The second panel starts open.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Exclusive accordion</title>
<style>
.accordion details {
border: 1px solid #ccc;
padding: 0.5rem 1rem;
}
.accordion details + details {
border-top: 0;
}
.accordion summary {
cursor: pointer;
font-weight: 600;
}
.accordion details[open] summary {
margin-bottom: 0.5rem;
}
</style>
</head>
<body>
<h1>Help center</h1>
<div class="accordion">
<details name="help">
<summary>Shipping</summary>
<p>Orders ship within two business days.</p>
</details>
<details name="help" open>
<summary>Returns</summary>
<p>You can return items within 30 days of delivery.</p>
</details>
<details name="help">
<summary>Payment</summary>
<p>We accept cards and bank transfer.</p>
</details>
</div>
</body>
</html>Click "Shipping" and "Returns" closes. Click "Shipping" again and it closes, leaving every panel collapsed. This is the main difference from radio buttons: a radio group always keeps one choice selected, while a details group allows zero or one open panel.
How the grouping rules work
The behavior follows a small set of rules. Most bugs come from forgetting one of them.
- Matching is by exact string.
name="faq"andname="FAQ"are different groups. Whitespace counts too. - An empty or missing name means no group.
name=""does not put elements in a shared empty group. Those elements stay independent. - Elements do not have to be siblings. Two
detailselements in different containers share a group if they are in the same tree and have the same name. You can put other elements between panels, such as headings or a wrapperdivfor each item. - The group is scoped to a tree. The document and each shadow root are separate trees. Two
detailselements with the same name, one in the page and one inside a web component's shadow root, do not affect each other. Two components that each usename="item"internally do not interfere. - Closing is the only side effect. Opening a member closes the others. Closing a member does not open anything.
The following table shows what happens in a three-panel group for common actions.
| Action | A | B | C |
|---|---|---|---|
| Initial state | closed | open | closed |
| User opens A | open | closed | closed |
| User opens C | closed | closed | open |
| User closes C | closed | closed | closed |
| Script sets `B.open = true` while C is open | closed | open | closed |
The last row matters. The exclusivity rule applies to any change of the open state, including changes made from JavaScript or by editing the attribute in the developer tools. It is not limited to clicks.
The sequence of events
When the user opens a panel in a group, the browser changes two elements. Each one fires its own toggle event.
That placeholder is not used. The diagram follows.
The browser queues toggle events and delivers them asynchronously. Do not assume that the code after details.open = true runs after the listener. It runs before.
Setting the initial state
The open attribute from the earlier chapter still decides what shows on first load. Put it on at most one member of a group.
<details name="steps" open>
<summary>Step 1: Create an account</summary>
<p>Enter your email address and choose a password.</p>
</details>
<details name="steps">
<summary>Step 2: Verify your email</summary>
<p>Click the link we send you.</p>
</details>If you write open on several members of the same group, the markup contradicts the rule that only one can be open. The browser resolves this by closing the extras, and the specification's algorithm decides which one stays open. Do not depend on it. If you need to choose which panel starts open, put open on that panel only. This is a common error when developers copy the first panel's markup to make the others.
Controlling a group from JavaScript
The name attribute is reflected as a name property on HTMLDetailsElement, in the same way open is reflected as a property. You can read and change it.
const panels = document.querySelectorAll('details[name="help"]');
panels.forEach((panel) => {
panel.addEventListener('toggle', (event) => {
const title = panel.querySelector('summary').textContent;
console.log(`${title}: ${event.newState}`);
});
});
// Open the Payment panel. The browser closes whichever panel was open.
const payment = [...panels].find((p) => p.querySelector('summary').textContent === 'Payment');
payment.open = true;The ToggleEvent object has oldState and newState properties, each "open" or "closed". Older browsers deliver a plain Event without them. If you need to support those, read panel.open inside the handler instead.
Because opening one panel produces two events, a handler that does work on every toggle must check which direction it is going. For example, a handler that lazy-loads content should act only when newState is "open".
document.querySelectorAll('details[name="help"]').forEach((panel) => {
panel.addEventListener('toggle', () => {
if (!panel.open) return;
if (panel.dataset.loaded) return;
panel.dataset.loaded = 'true';
console.log('Load content for', panel.id || 'panel');
});
});Expand all does not fit
A common request is an "Expand all" button. With a shared name this cannot work, because each open = true closes the previous panel. Only the last one stays open. You have two choices:
- Do not use a shared
nameon that page, and use independent panels. - Remove the
nameattribute when the user asks to expand all, then restore it on collapse.
const group = document.querySelectorAll('details[name="help"]');
const button = document.querySelector('#toggle-all');
let expanded = false;
button.addEventListener('click', () => {
expanded = !expanded;
group.forEach((panel) => {
if (expanded) {
panel.removeAttribute('name');
panel.open = true;
} else {
panel.open = false;
panel.setAttribute('name', 'help');
}
});
});Removing name before opening matters. If you set open = true first, the group closes the earlier panels immediately. Setting name back after closing everything means the group never has two open members at the moment it is rebuilt.
Styling a group
The selectors from the styling chapter work unchanged. Two points are specific to groups.
First, the details[open] selector matches at most one member of a group at any time, so you can use it to highlight the active item.
details[name="help"] {
border: 1px solid #ccc;
padding: 0.5rem 1rem;
}
details[name="help"][open] {
border-color: royalblue;
background: #f4f7ff;
}
details[name="help"] + details[name="help"] {
border-top: 0;
}Second, you can select a whole group by its name with an attribute selector. This keeps accordion styles separate from standalone disclosure widgets on the same page.
Do not rely on CSS to enforce the exclusivity. Hiding panels with display: none through a class has no effect on the open state, and the two can disagree.
Keyboard use and accessibility
A named group does not change how each panel works for keyboard and assistive technology users.
- Each
summaryis a tab stop. Press Tab to move between summaries. - Enter or Space toggles the focused panel.
- Arrow keys do nothing. This differs from the ARIA accordion and tabs patterns, where arrows can move focus.
- Screen readers announce each summary as a disclosure with an expanded or collapsed state. They do not announce the group.
Because the semantics are already correct, avoid adding ARIA roles. Setting role="tablist" or role="button" on these elements can replace the built-in behavior and make things worse.
One side effect to know about: when the user opens a panel, the browser closes another one. Content the user was reading or focus inside it can disappear. If the closing panel contained the focused element, focus moves to the document body in some browsers. For long panels with form controls or links, consider whether an exclusive group helps the user. A user comparing two answers cannot keep both visible.
Find-in-page works with closed panels in current Chromium browsers. A match inside a collapsed details opens it. In a named group this also closes the panel that was open. That is expected, but it can surprise a user who is searching and watching the page change.
Browser support and a fallback
The name attribute on details is newer than details itself. It shipped in Chromium 120, Safari 17.2 and Firefox 130. Check a current compatibility table before relying on it.
A browser that does not understand name ignores it. The panels then act as independent disclosure widgets. That is a graceful failure, because all content stays reachable. For many sites this is enough and you need no fallback.
If you need exclusive behavior everywhere, detect support and add a script that does the closing.
if (!('name' in HTMLDetailsElement.prototype)) {
document.addEventListener('toggle', (event) => {
const panel = event.target;
if (!(panel instanceof HTMLDetailsElement) || !panel.open) return;
const name = panel.getAttribute('name');
if (!name) return;
document
.querySelectorAll('details[open]')
.forEach((other) => {
if (other !== panel && other.getAttribute('name') === name) {
other.open = false;
}
});
}, true);
}The listener uses the capture phase on document because toggle does not bubble. Comparing with getAttribute avoids building a selector from the name, so unusual characters in a name cannot break the query.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Several panels stay open | Names differ in case or spelling, or one panel has no `name` | Use one identical value on every member |
| Opening a panel closes unrelated panels | Two groups reuse the same name | Give each accordion a unique name |
| Panels in a component ignore the page's group | They are in a shadow root | Use a name inside each tree |
| Two panels start open | `open` copied onto several members | Keep `open` on one panel |
| "Expand all" opens only one panel | Group rule closes the earlier ones | Remove `name` first, as shown above |
| Handler runs twice per click | One event for the closing panel, one for the opening panel | Check `newState` or `panel.open` |
When a named group is the right choice
Use a named group when the content is a short list of questions, steps or sections, and showing one at a time is acceptable. It is simple, needs no script, and follows built-in keyboard and screen reader behavior.
Choose independent details elements, or a custom component, when:
- Users need to compare several panels at once.
- You need an "Expand all" control.
- You need arrow-key navigation or exactly one panel always open.
- You need to cancel a toggle, since
togglefires after the state has changed and cannot be prevented.
Exercise
A page has three details elements in one accordion. You open the first, then call third.open = true from a script. Which panels are open afterward, how many toggle events fire, and which newState value does each carry? Assume all three share name="faq".
Show answer
Only the third panel is open. Two toggle events fire: one on the first panel with newState of "closed", and one on the third panel with newState of "open". The browser closes the first panel because it shares the name with the third. The events are delivered after the script finishes its current task.
Exercise
A teammate wrote <details name="Faq"> on two panels and <details name="faq"> on a third, and reports that the third panel stays open when the others are opened. Explain why, and give the fix.
Show answer
Group names are compared as exact, case-sensitive strings, so Faq and faq are separate groups. The third panel is in its own group, and nothing closes it. Change all three to the same value, such as name="faq".
Exercise
Write the JavaScript for an "Expand all" button that works with a group of details elements sharing name="help". Explain why the order of operations matters.
Show answer
Remove the name attribute from each panel, then set open = true on each one. To collapse, set open = false on each, then set the name attribute back to help. Order matters because setting open = true on a panel that still has the name makes the browser close the other open members of its group. Only the last panel would remain open.