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>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…