Here is my code.
JavaScript
x
14
14
1
<details>
2
<summary>1</summary>
3
Demo 1
4
</details>
5
6
<details>
7
<summary>2</summary>
8
Demo 2
9
</details>
10
11
<details>
12
<summary>3</summary>
13
Demo 3
14
</details>
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.
Advertisement
Answer
Another approach, slightly shorter, slightly more efficient, without dependencies, and without onclick attributes in the HTML.
JavaScript
1
14
14
1
// Fetch all the details element.
2
const details = document.querySelectorAll("details");
3
4
// Add the onclick listeners.
5
details.forEach((targetDetail) => {
6
targetDetail.addEventListener("click", () => {
7
// Close all the details that are not targetDetail.
8
details.forEach((detail) => {
9
if (detail !== targetDetail) {
10
detail.removeAttribute("open");
11
}
12
});
13
});
14
});
JavaScript
1
11
11
1
<details>
2
<summary>1</summary>Demo 1
3
</details>
4
5
<details>
6
<summary>2</summary>Demo 2
7
</details>
8
9
<details>
10
<summary>3</summary>Demo 3
11
</details>