So I have a number of details/summary tags and I want to create an expand all / contract all button however for some reason I can’t seem to get it working right.
So first I did this
Code: Select all
<details open>
<summary>item 1</summary>
<p>some content</p>
</details>
var has_open = document.querySelector("details").hasAttribute("open");
alert(document.querySelector("details > summary").innerHTML);
Code: Select all
<details>
<summary>item 1</summary>
</details>
<details open>
<summary>item 2</summary>
</details>
<details open>
<summary>item 3</summary>
</details>
var has_open = document.querySelectorAll("details").hasAttribute("open");
for (i = 0; i < has_open.length; i++)
{
alert(document.querySelectorAll("details > summary")[i].innerHTML);
}
so my question is what am I missing because as far I can tell the above code should work and should return a list of all details elements that have the open property and should then alert item 2, item 3 as those are the ones that have the open property.TypeError: document.querySelectorAll(...).hasAttribute is not a function
why is it that if I want to check just a single details element and alert out the content of the summary tag everything works fine but when I try to do the same thing for multiple details elements it wont work properly.
in any event here is what I have so far
Code: Select all
<button onclick="toggle()">expand all</button>
// Get the div that has the .show class then get a list of all detail elements within it
var details = document.querySelector('.show').querySelectorAll("details");
//loop through the list of details elements one at a time starting at index 0.
for (i = 0; i < details.length; i++)
{
// Get a list of detail elements that have the open attribute
var has_open = details[i].hasAttribute("open");
}
if(has_open) //if any of the details elements have the open attribute
{
//loop through the list of detail elements one at a time starting at index 0.
for (i = 0; i < details.length; i++)
{
// for each detail element that have the open attribute remove the open attribute
details[i].removeAttribute("open");
// Get the expand all / collapse all button and toggle its text
document.querySelector("button").innerHTML = "expand all"
}
}
else //if any of the detail elements don't have the open attribute
{
//loop through the list of detail elements one at a time starting at index 0.
for (i = 0; i < details.length; i++)
{
// for each detail element that does not have the open attribute add the open attribute.
details[i].setAttribute("open", "true");
// Get the expand all / collapse all button and toggle its text
document.querySelector("button").innerHTML = "collapse all"
}
}