FLASH SALE Get 20% OFF everything using the coupon code: FLASH20 View WordPress Plugins →

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

on in JavaScript DOM
Last modified on

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) {
                    detail.removeAttribute("open");
                }
            });
        });
    });
}

Related posts