I have a problem with my for loop:
`
let accordions = document.getElementsByClassName("faq-accordion");
let accordions_content = document.getElementsByClassName("faq-accordion__content");
let elementCounter = 0;
for(let accordion of accordions) {
accordions[elementCounter].addEventListener("click", function() {
console.log(accordions_content[elementCounter]);
})
elementCounter++;
}
})`
in my loop "accordions_content[elementCounter]);" does not exist but outside my loop is does exist and outside my eventlistener too, so whats the problem here?
I have alredy checked it, if the variable works outside my loop.
My HTML:
<div class="faq">
<div class="faq-accordion">
<div class="faq-accordion__headline">
<h5>Das ist eine Headline</h5>
</div>
<div class="faq-accordion__content">
<p>Das ist ein Text</p>
</div>
</div>
<div class="faq-accordion">
<div class="faq-accordion__headline">
<h5>Das ist eine Headline</h5>
</div>
<div class="faq-accordion__content">
<p>Das ist ein Text</p>
</div>
</div>
<div class="faq-accordion">
<div class="faq-accordion__headline">
<h5>Das ist eine Headline</h5>
</div>
<div class="faq-accordion__content">
<p>Das ist ein Text</p>
</div>
</div>
</div>
2
Answers
Here is a fix
Since you posted your html, here is a snippet that match better your case.