0

I have the problem that when executing a script the error message appears:

Cannot read property 'addEventListener' of null

My JavaScript code:

var bghtooltipin  = document.getElementById('bgh-tooltipin1');
var bghtooltipout = document.getElementById('bgh-tooltipout1');
bghtooltipin.addEventListener('mouseover', mouseOver);
bghtooltipin.addEventListener('mouseout', mouseOut);

I looked at a lot of troubleshooting tips but didn't find anything that would fix my problem.

Paul Roub
  • 35,100
  • 27
  • 72
  • 83
Luca Kammerer
  • 339
  • 2
  • 11
  • Does this answer your question? [Why does jQuery or a DOM method such as getElementById not find the element?](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – Ivar Dec 14 '20 at 14:23

2 Answers2

1

Cannot read property addEventListener of null would happen when you're trying to access that property of null. The error just means that, if you're doing this:

myElement.addEventListener("click", function () {
    //some code
});

then myElement isn't defined like you think it is. Without any code, I can't help anymore, but my best advice is to go to where you define myElement. Likely, that line has something wrong with it.

Jaden Baptista
  • 382
  • 2
  • 13
0

You have to write your javascript at the end of body or initialize it with DOMContentLoaded. The problem is your, document is not complete at the time, when you try to select your element.

<script>
document.addEventListener('DOMContentLoaded', function() {
    document.querySelector('#elem').addEventListener('click', function() { this.innerText += '!'; });
});
</script>

<button id="elem">Click me</button>
dipser
  • 376
  • 2
  • 5