Search code examples
javascriptaccordion

How to Fix my Code to add Collapse All div to Vanilla JS Accordion?


I have experience working with HTML and CSS, but I'm just starting to learn JS, so my code probably reflects as much. I've inserted a vanilla JS accordion into my website, but I want to add (preferrably multiple) Collapse-All links on the page as well. This is my accordion HTML, CSS, and JS, adapted from W3Schools (https://www.w3schools.com/howto/howto_js_accordion.asp):

   <h3 class="accordion">
     ***
   </h3>
   <div class="panel">
     ***
   </div>
   <h3 class="accordion">
     ***
   </h3>
   <div class="panel">
     ***
   </div>
   ...
   div.panel {
     max-height: 0;
     overflow: hidden;
     transition: 0.5s ease-out;
   }
   var accordion = document.getElementsByClassName("accordion");
   var i;

   for (i = 0; i < accordion.length; i++) {
     accordion[i].addEventListener("click", function() {
       var panel = this.nextElementSibling;
       if (panel.style.maxHeight) {
         panel.style.maxHeight = null;
       } else {
         panel.style.maxHeight = panel.scrollHeight + "px";
       }
     });
   }

The following is my own attempt at adding a collapse-all functionality based on the accordion JS, supposedly to iterate through all my collapse-all links for a click event, and then iterating through all accordion panels to find and close all panels that are open:

   <div class="collapse">
     Collapse All
   </div>
   ...
   <div class="collapse">
     Collapse All
   </div>
   ...
   var collapse = document.getElementsByClassName("collapse");
   var j;

   for (j = 0; j < collapse.length; j++) {
     collapse[j].addEventListener("click", function() {
       var panelAll = document.getElementsByClassName("panel");
       for (k = 0; k < panelAll.length; k++) {
         if (panelAll.style.maxHeight) {
           panelAll.style.maxHeight = null;
         }
       }
     });
   }

However, at the line "if (panelAll.style.maxHeight)" within the final for-loop, I'm getting a console error because panelAll.style.maxHeight is undefined. This is where I'm stuck, because I don't get any console errors in the original JS for the accordion when panelAll.style.maxHeight is null/undefined. Is there any simple fix to my problem, or would I need to re-code the entire accordion JS in order to add a collapse-all functionality (in which case I'll probably forgo it)? Thanks for any input.


Solution

  • You should try panelAll[k].style.maxHeight because panelAll is an array as document.getElementsByClassName returns a collection.