0

In order to avoid mistake: "Cannot read property 'addEventListener' of null", there are 3 solutions:

  1. Put the scripts in the bottom of the page.
  2. Call the attach code in the load event.
  3. Use jQuery library and it's DOM ready event.

(Javascript: Uncaught TypeError: Cannot call method 'addEventListener' of null)

How to add addEventListener in the load event (solution #2), why it doesn't work?

html:

<!DOCTYPE html>
<html lang="en">
<head><script src="script.js"></script></head>
<body><a href="http://google.com" id="link">DELETE</a></body>
</html>

js:

function del(e){
    var target = e.target;
    var cont = target.parentNode;
    target.preventDefault(e);
    cont.removeChild(target);
}
var link = document.getElementById("link");
document.addEventListener("load", function() { link.addEventListener("click", del); });
Community
  • 1
  • 1
Alexander
  • 55
  • 5

2 Answers2

0

You are referencing the element before it is rendered. You need to put the var link = ... inside the onload or move the script to the bottom of the body.

Your code has a bunch of issues, below is it running:

function del(e){
    var target = e.target;
    var cont = target.parentNode;
    e.preventDefault();  //needs to be e, not target
    cont.removeChild(target);
}

window.addEventListener("load", function() {  //needs to be window, there is no document load event
    var link = document.getElementById("link");  //inside of the onload
    link.addEventListener("click", del); 
});
<a href="#" id="link">DELETE</a>
epascarello
  • 185,306
  • 18
  • 175
  • 214
  • if to put "var link..." inside onload, it doesn't work, too( - function del(e){ var target = e.target; var cont = target.parentNode; target.preventDefault(e); cont.removeChild(target); } function myFunc() { var link = document.getElementById("link"); link.addEventListener("click", del); } document.addEventListener("load", myFunc); – Alexander Apr 20 '16 at 14:27
0

The reason you can't assign an event handler to something before it exists is because you can't fetch the element out of the DOM before it exists.

You've moved the code that assigns the event handler into a load handler, but you've left the code that tries to fetch it from the DOM outside the load handler.

You need to move the var link = document.getElementById("link"); inside too.


Additionally, the load event for an HTML page fires on the window object and not the document object.

Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205
  • function del(e){ var target = e.target; var cont = target.parentNode; target.preventDefault(e); cont.removeChild(target); } function myFunc() { var link = document.getElementById("link"); link.addEventListener("click", del); } document.addEventListener("load", myFunc); it doesn't work too :( – Alexander Apr 20 '16 at 14:23