The exclusive accordion

A variation of the accordion pattern is the exclusive accordion, in which only one of the disclosure widgets can be opened at the same time.

To create an exclusive accordion on the web you add a name attribute to the

elements. When this attribute is used, multiple
elements that have the same name value form a semantic group and they will behave as an exclusive accordion. When you open one of the
elements from the group, the previously opened one will automatically close.

<details name="learn-css">
  <summary>Welcome to Learn CSS!</summary>
  <p>…</p>
</details>
<details name="learn-css">
  <summary>Box Model</summary>
  <p>…</p>
</details>
<details name="learn-css">
  <summary>Selectors</summary>
  <p>…</p>
</details>

Polyfill the exclusive accordion

With the following JavaScript it’s possible to polyfill the behavior of the exclusive accordion. The code relies on the toggle event of the

element.

When a

element with a name opens, the code finds the other open
elements with the same value for the name attribute and closes them.

document.querySelectorAll("details[name]").forEach(($details) => {
  $details.addEventListener("toggle", (e) => {
    const name = $details.getAttribute("name");

    if (e.newState == "open") {
      document
        .querySelectorAll(`details[name=${name}][open]`)
        .forEach(($openDetails) => {
          if (!($openDetails === $details)) {
            $openDetails.removeAttribute("open");
          }
        });
    }
  });
});