How to Open Only One Details/Summary Element at a Time

Ciprian on Tuesday, December 27, 2022 in JavaScript DOM

NEW! Learn JavaScript by example. Code snippets, how-to's and tutorials. Try now!

Let’s suppose you want to build a simple accordion or a help section, and you want to use a <details> element and only have one open at a time. Here is how to do it:

 * Details/summary HTML element
 * Only open one element at a time
if (document.querySelector('details')) {
    // Fetch all the details elements
    const details = document.querySelectorAll('details');

    // Add onclick listeners
    details.forEach((targetDetail) => {
        targetDetail.addEventListener("click", () => {
            // Close all details that are not targetDetail
            details.forEach((detail) => {
                if (detail !== targetDetail) {

Related posts

Leave a Reply

Your email address will not be published. Required fields are marked *