I am attempting to create an accordion using Vanilla JavaScript, but I have encountered an issue. When there is a child div element inside the header of the accordion, it does not seem to work and I'm unsure why. However, if there is no child div element, the accordion functions properly.
var coll = document.getElementsByClassName("m40__grid__item");
coll[i].addEventListener("click", function (evnt) {
let target = evnt.target;
if ( !target.matches('.m40__grid__item') ) {
target = target.closest('.m40__grid__item');
}
const currClassList = target.classList;
if (currClassList.contains("active")) {
evnt.target.classList.remove("active");
var content = evnt.target.nextElementSibling;
content.style.maxHeight = null;
} else {
for (var j = 0; j < coll.length; j++) {
coll[j].classList.remove("active");
coll[j].nextElementSibling.style.maxHeight = null;
}
this.classList.toggle("active");
var content = this.nextElementSibling;
if (content.style.maxHeight) {
content.style.maxHeight = null;
} else {
content.style.maxHeight = content.scrollHeight + "px";
}
}
});
}
<div class="m40__grid">
<div class="m40__grid__item">
<div class="test">
This header doesn't work
</div>
</div>
<div class="m40__grid__item--full-width">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>
<div class="m40__grid__item">Click me!</div>
<div class="m40__grid__item--full-width">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>
</div>
The code pen showcasing my issue can be found here: https://codepen.io/mrsalami/pen/WNrBboR?editors=1111