Omeka站点Accordion折叠按钮失效:TypeError: panel is null问题求助
Let's break down why your accordion works when the script is inline but breaks when moved to a separate JS file (even with DOMContentLoaded):
The Root Cause
Look at your HTML structure:
<p><button class="accordion">Section 1</button></p> <div class="panel">...</div>
When you click the accordion button, this.nextElementSibling tries to grab the element immediately after the button. But the button is wrapped inside a <p> tag—there are no elements directly after the button inside that paragraph, so panel ends up being null, hence the error.
The Fix
Instead of targeting the button's next sibling, you need to target the parent paragraph's next sibling (which is your .panel div). Here's how to adjust your JS:
Corrected JavaScript
/* Script for accordion buttons */ document.addEventListener("DOMContentLoaded", function () { var acc = document.getElementsByClassName("accordion"); var i; for (i = 0; i < acc.length; i++) { acc[i].addEventListener("click", function() { this.classList.toggle("active"); // Get the parent <p> element, then its next sibling (the panel) var panel = this.parentElement.nextElementSibling; if (panel.style.maxHeight) { panel.style.maxHeight = "none"; } else { panel.style.maxHeight = panel.scrollHeight + "px"; } }); } });
Additional Notes
- You had an unused
var panel = document.getElementsByClassName("panel");line at the top of your script—you can safely remove that to clean up the code. - Your CSS and HTML structure are fine once the JS selector is fixed, so no changes needed there.
- Even though you used
DOMContentLoaded, the issue wasn't timing—it was incorrect element targeting. The inline script might have appeared to work due to a different execution context, but the core problem was always the selector.
Test this updated JS file, and your accordion should work as expected in your Omeka site!
内容的提问来源于stack exchange,提问作者Gayle S.

