Automatically close all the other <details> tags after opening a specific <details> tag

rohan_vg picture rohan_vg · May 25, 2013 · Viewed 10.2k times · Source

Here is my code.

What I want to do is -- if the details of any single <details> tag is open and I open/view another <details> tag, then the earlier one should close/hide/minimize.

How can this be achieved?

I'm aware the <details> tag is not supported in IE or Edge.

Answer

Quentin Roy picture Quentin Roy · May 3, 2016

Another approach, slightly shorter, slightly more efficient, without dependencies, and without onclick attributes in the HTML.

// Fetch all the details element.
const details = document.querySelectorAll("details");

// Add the onclick listeners.
details.forEach((targetDetail) => {
  targetDetail.addEventListener("click", () => {
    // Close all the details that are not targetDetail.
    details.forEach((detail) => {
      if (detail !== targetDetail) {
        detail.removeAttribute("open");
      }
    });
  });
});
<details>
  <summary>1</summary>Demo 1
</details>

<details>
  <summary>2</summary>Demo 2
</details>

<details>
  <summary>3</summary>Demo 3
</details>