I'm creating an accordion using HTML, CSS and JavaScript. However, I'm experiencing this problem where the accordion would just not show a message when I click on a label because of this message:
Uncaught TypeError: Cannot read properties of undefined (reading 'style')
var accordionLabels = document.querySelectorAll(".accordion-label");
var accordionContent = document.querySelectorAll(".accordion-content");
for (var x = 0; x < accordionLabels.length; x++) {
accordionLabels[x].addEventListener("click", function() {
accordionContent[x].style.display = "block";
});
};
body {
font-family: Arial;
}
.accordion-label,
.accordion-content {
width: 50%;
}
.accordion-label {
background-color: green;
color: #eee;
padding: 10px;
}
.accordion-label:hover {
opacity: 0.8;
}
.accordion-content {
padding: 10px;
display: none;
}
<div class="accordion-label">What's up?</div>
<div class="accordion-content">The sky.</div>
<br>
<div class="accordion-label">Who invented the World Wide Web?</div>
<div class="accordion-content">Tim Berners-Lee</div>
<br>
<div class="accordion-label">What is the main ingredient used in Guacamole?</div>
<div class="accordion-content">Avocado</div>
<br>
<div class="accordion-label">What is the spiciest pepper in the world?</div>
<div class="accordion-content">Carolina Reaper</div>
Here in this JavaScript code, I'm trying to loop through each accordion in the page so that when they're clicked, a message is displayed for one of them.