Anyone know if there is a way to create an expand all link for pages that use the semantic <details>
tag? I managed to create a link that would auto-open closed details: Link to details section that expands details section as well
Now I'm trying to add a link that will expand all <details>
.
I'm guessing you can do it with javascript but I'm weak there. Something to the effect of clicking a link that initiates a script that finds all "<details in the html and inserting the word "open" before displaying the html. Little help would be appreciated.
So far I'v got
<button onclick="openAll()">Expand All</button>
<script>function openAll() {
var x = document.getElementsByTagName("details");
var i;
for (i = 0; i < x.length; i++) {
x[i].setAttribute("open", "true");
}
</script>
The below works for the first <details>
tag but I guess my loop in the above is not correct ...
<script>
function openAll() {
document.getElementsByTagName("details")[0].setAttribute("open", "true");
}
</script>
The below is the dummy html that I'm testing on
<details>Hello World<summary>summary</summary>lost</details>
<details>another<summary>good night moon</summary>find me</details>
The solutions didn't work for me. So, I altered @testing123 solution to get it to work with a complete example.
So zer00ne's solution seems to sometimes work in the browsers (Chrome / Firefox). Sometimes on the second click it works. Sometimes on the first. Sometimes not at all. Maybe because the
details
tag is still not fully supported?I went with the solution below ... just has an absolute endpoint at 31 instead of stop at end.
UPDATE
OP requested that the first 6
<detail>
s be excluded. Swapped out.forEach()
method forfor
loop.See Snippet 2
Use the
.open
attribute of<details>
. It's true if open false if closed. Details commented in Snippet.SNIPPET 1
SNIPPET 2