Hello, I have the following code from w3schools, opening an closing an accordion-list (panel). (CSS works well!!) I wanted to augment the version: When I open a panel all the other panels should close. I tried to use the second loop in /**/, however this does not work. Any suggestions? Thanks a lot! (function () { var acc = document.getElementsByClassName("accordion"); var i,j; for (i = 0; i < acc.length; i++) { acc[i].addEventListener("click", function() { /* for (j = 0; j < acc.length; j++) { acc[i].nextElementSibling.style.display = "block"; } */ this.classList.toggle("active"); var panel = this.nextElementSibling; if (panel.style.display === "block") { panel.style.display = "none"; } else { panel.style.display = "block"; } }); } })(); Code (JavaScript):
Assuming you don't want it animated, this is NOT JavaScript's job anymore. There's the :checked attribute on inputs that you can leverage to trigger your accordions. If you only want one open, use type="radio" with the same name. <ul class="accordionMenu"> <li> <input type="radio" name="menuDepth1" id="toggle_section1" class="toggle" hidden> <label for="toggle_section1">Section 1</label> <ul> <li>Test1-1</li> <li>Test1-2</li> <li>Test1-3</li> <li>Test1-4</li> <li>Test1-5</li> <li>Test1-6</li> </ul> </li><li> <input type="radio" name="menuDepth1" id="toggle_section2" class="toggle" hidden> <label for="toggle_section2">Section 2</label> <ul> <li>Test2-1</li> <li>Test2-2</li> <li>Test2-3</li> <li>Test2-4</li> <li>Test2-5</li> <li>Test2-6</li> </ul> </li><li> <input type="radio" name="menuDepth1" id="toggle_section3" class="toggle" hidden> <label for="toggle_section3">Section 3</label> <ul> <li>Test3-1</li> <li>Test3-2</li> <li>Test3-3</li> <li>Test3-4</li> <li>Test3-5</li> <li>Test3-6</li> </ul> </li> </ul> Code (markup): .accordionMenu .toggle { /* fix for IE so <label> will still toggle their "for" */ display:block; position:absolute; left:-999em; } .accordionMenu .toggle ~ label { /* WHY isn't this the default for <label>?!? Oh that's right, nobody ***ing knows what LABEL is even for much less how to use it right. */ cursor:pointer; } .accordionMenu .toggle:checked ~ label { /* set the style you want for it when checked here. You could use generated content to add/remove a character like the right-pointing utf-8 triangles. */ background:#000; color:#FFF; } .accordionMenu .toggle ~ ul { /* APo insstead of display:none so search doens't think we're content cloaking */ position:absolute; left:-999em; top:-999em; } .accordionMenu .toggle:checked ~ ul { position:static; /* will now ignore the top/left values, showing it. */ } Code (markup): NOT JAVASCRIPTS JOB ANYMORE!!! Also remember that if you don't need the "just one open" there's the DETAILS and SUMMARY tags which can also do this without JavaScript -- and even more fun can do so without CSS' help either.