0

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.

isherwood
  • 58,414
  • 16
  • 114
  • 157
mantot123
  • 103
  • 1
  • 5
  • Protip: Don't use line breaks for spacing. That's not their purpose. Use margin, padding, or flexbox features. – isherwood Apr 28 '23 at 13:06

0 Answers0