0

"Cannot read property 'addEventListener' of null"

my code is presenting to me this error in the title the code : //gets the element vel by its id and sets it to a variable var vel = document.getElementById("vel"); vel.addEventListener("click", function() { //gets these 2 elements by thier ids var d = document.getElementById("d"); var t = document.getElementById("t"); //sets the result var var result = d / t; //get the <p> tag by its id and then puts the result into it. var x = document.getElementById("res"); x.innerHTML = result });

14th Nov 2018, 3:46 AM
Youssef Hammad
Youssef Hammad - avatar
5 Réponses
+ 8
It's just bcz your JS gets loaded before the HTML part and so it can't find that element. Just put your whole JS code inside a function which will be called when the window gets loaded. You can do like this is your JS window.onload= function (){ //Your entire JS code here }
14th Nov 2018, 4:36 AM
Шащи Ранжан
Шащи Ранжан - avatar
+ 4
It means there's no element with id "vel" Maybe check your html
14th Nov 2018, 3:56 AM
Flandre Scarlet
Flandre Scarlet - avatar
+ 3
In addition to what Flandre Scarlet said, make sure you are accessing the element after it has been created in the DOM. Something like document.onload would do the trick.
14th Nov 2018, 4:00 AM
Kishalaya Saha
Kishalaya Saha - avatar
+ 3
replying to shashi ranja: thanks a lot
15th Nov 2018, 3:45 PM
Youssef Hammad
Youssef Hammad - avatar
+ 1
It is because the variable is not defined yet. You probably have not saved the html yet or have not defined it yet.
16th Sep 2020, 6:33 AM
Farhad Baloch
Farhad Baloch - avatar