Home javascript Cannot read property 'addEventListener' of null

Cannot read property ‘addEventListener’ of null




I have two different functions for events on click, one works, the other does not, but if you swap the positions, on the contrary, the second one which became the first works, and the first one does not.
Both of these functions are written for different HTML pages. Apparently this is the problem. The interpreter stumbles and cannot read property addeventlistener of null?
but how else to do it? not to write a separate script for each page?

Answer 1, authority 100%

The answer is very simple, check before adding a listener to an element.

For example, before the lines where you add the listener, do something like this:

if (humburger) {
  humburger.addEventListener ....

And also for the second case

Answer 2

In the html file where you connect, write the defer attribute.

& lt; script src = "script.js" defer & gt; & lt; / script & gt;
Previous articleOkHttp 3 for Beginners
Next articleNone python value

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions