How do I make a button toggle a <details>.open attribute?

Hello. I need help with using a button to toggle the details open attribute. My JavaScript code can open the element, but not close it. Link: https://glitch.com/edit/#!/apricot-glimmer-chokeberry/ or you can click this. Thank you.

1 Like

In script.js, you’ve got this line:

details.setAttribute("open", !(details.getAttribute(id)));

which means “set the open attribute to ‘true’ if the details element doesn’t have an attribute called whatever id is (in this case, ‘a’), or, that attribute is blank”. Which I don’t think is what you meant , seeing as in the alert above you have details.getAttribute("open"), which makes far more sense.

1 Like

The simplest way to do this is with the JavaScript open property:

detailsElement.open = !detailsElement.open;

Your Glitch project was trying to manipulate the HTML open attribute instead of the JavaScript open property. While it’s possible to do it that way, an important difference between the two is that if the HTML attribute receives any value, that will open the element. To close it, you must remove the attribute altogether:

detailsElement.removeAttribute("open");
1 Like