-2

please help me with the following code, it shows "Uncaught TypeError: Cannot read property 'addEventListener' of null".

let btn = document.getElementById("btn");

function function1(){
  let ourRequest = new XMLHttpRequest();
  ourRequest.open('GET', 'https://learnwebcode.github.io/json-example/animals-1.json');
  ourRequest.onload = function() {
  let ourData = JSON.parse(ourRequest.responseText);
  console.log(ourData[0]);
  };
  ourRequest.send();
};
btn.addEventListener("click", function1(), false);

i simply dont see how its null.... :/

thanks in advance!

ptaku
  • 17
  • 1
  • 2

1 Answers1

4

If btn is null then it means there's no element with id property equal to btn. Double check your HTML. Also please make sure that you put your script just before the end of the body tag. Your script may be loaded before the DOM is and that can also be the issue.

PS. Even if you fix the issue with missing HTML element your code won't work. You're invoking your callback instead of passing it to addEventListener. That will result in passing undefined to event listener. Change:

btn.addEventListener("click", function1(), false);

to:

btn.addEventListener("click", function1, false);
lukaleli
  • 2,867
  • 3
  • 18
  • 31