In order to avoid mistake: "Cannot read property 'addEventListener' of null", there are 3 solutions:
- Put the scripts in the bottom of the page.
- Call the attach code in the load event.
- 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); });