Cannot read properties of undefined (reading 'display')

I have not worked with the DOM in a while, and I decided to do a little refresher project. Needless to say, it is not going well. I am trying to get it so that for every arrow that is pressed the display will toggle and show the answer. If it is pressed again the answer will go back to display:none;

I got it working if I select the first arrow with querySelector, but when I tried it with querySelector all I get the error "Cannot read properties of undefined (reading ‘display’)

My pen:

showDisplay is just the first element with the hidden-answer class. It will always be the same one. You can use the click target and do DOM traversal.

Inside the click handler get the event.target (click target) and traverse the DOM up to the parent container and then to the next sibling element.

event.target.parentElement.nextElementSibling

spoiler
document.querySelectorAll("img").forEach((item) => {
  item.addEventListener("click", (event) => {
    const textBlock = event.target.parentElement.nextElementSibling;
    if (textBlock.style.display === "none") {
      textBlock.style.display = "block";
    } else {
      textBlock.style.display = "none";
    }
  });
});
1 Like

Thank you. Its clear that I need to spend some time here and go back over everything.

If anything is unclear just ask.

Just to help maybe clear it up a bit.

event.target is the image that was clicked.

parentElement is the clicked image parent container.

nextElementSibling is the div element that comes after the clicked image parent container.