I want to create an accordion in my webshop's cart drawer but I can't find a way to fix my issue.
What is happening here is that I get the element but as soon as the drawer is re-rendered then my reference is lost. Because the DOM dynamically changes, I should not do it this way. Instead, I should use event delegation so that my code can still work even when things are re-rendered.
var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].addEventListener("click", function() {
this.classList.toggle("active");
var panel = this.nextElementSibling;
if (panel.style.display === "block") {
panel.style.display = "none";
} else {
panel.style.display = "block";
}
});
}
<button type="button" class="accordion">Expand me</button>
<div class="panel">
<p>Text here...</p>
</div>