0

This React app renders and works as expected but once I click on one of the buttons, it then logs the error "TypeError: Cannot set property 'innerText' of null" for line 78 of the code which is this line:

display.querySelector('h1').innerText = `${id} is playing`;

which is in the playSound function:

    this.audio.current.play();
    
    const id = this.audio.current.id;

    const parent = this.audio.current.parentNode;
    parent.classList.add('active');

    const display = parent.parentNode;
    display.querySelector('h1').innerText = `${id} is playing`;
  }

So my guess as to what is going on is that what is being identified as "null" in this case is the string h1 and so I tried to change what is in between the string so I could identify it differently based on how it appears in the code as <h1> but it still logged the same error. Unless I am off base and it isn't targeting h1, but display? I'm not sure. I also placed my <div id="app" class="container"></div> above the script tag in html so I don't think that is it (I saw that offered as a quick fix).

Here is the code in jsFiddle

Am I reading the error correctly as far as what is null?

Expected results: to display the text included on line 78 on Display, which works until one of the buttons is clicked.

Any help would be appreciated, thank you.

grimreaper
  • 35
  • 5
  • What's null is `display.querySelector('h1')`, meaning it can't find that element. Either it's not in the DOM, or you're not traversing through the DOM correctly when selecting parent nodes and such – Jayce444 Mar 11 '21 at 00:39
  • Which is the element? in it's entirety? I thought only what querySelector is accepting ('h1') is null. I'm going to see if It's in the DOM so I'd love clarification if you have a minute. Thank you! – grimreaper Mar 11 '21 at 00:47
  • I don't really get what you mean, but if you check the way `querySelector` works (https://developer.mozilla.org/en-US/docs/Web/API/Element/querySelector), it essentially just looks for the first descendant in the DOM that matches the selector you pass in. So in your case, `display.querySelector('h1')` looks for the first `

    ` tag that's a descendant of the `display` element. If it can't find any `h1` tags in that element's descendants, it will return null

    – Jayce444 Mar 11 '21 at 00:58

0 Answers0