简体   繁体   中英

Javascript Cannot read property 'addEventListener' of null errors

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.

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM