How to automatically close all details tags after opening a specific one

  • Accordions
  • Details
  • HTML details
How to automatically close all details tags after opening a specific one

I’ve been making use of the details element for a little while now. It is quite simply the quickest, simplest solution for adding an accordion to a website. But, unlike using a framework to add accordions, they don’t come with some of the perhaps expected behaviour for opening/closing.

For example, when you click to open one accordion, then click to open another, you might expect or want the currently open one to be closed, saving on page height and confusion as to which one you have just opened/closed.

Implementing a fix to close all non-active details elements

// 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");
      }
    });
  });
});

How it works

This snippet will check for all details elements on the page, and listen out for the click event on them. It will remove the [open] attribute on all details elements that don’t match the targetDetail – the one you just clicked.

Let's build something great

Interested in starting your own website project with me? Excellent! I'd love to talk to you about your idea.

Get in touch

I aim to reply within 48 hours.