Sunday, April 29, 2018

javascript - Uncaught TypeError: Cannot set property 'onclick' of null




I am creating an HTML page, Which is built using bootstrap. Here is the final HTML code and code of hello.js file:





document.getElementById("subm").onclick = function () {
alert("Hello WOrld");
}





Calculator










Calculator








































When I click on the button using submit then instead of alert I am getting error




Uncaught TypeError: Cannot set property 'onclick' of null





Can anyone please tell me why I am facing this error?? Help to resolve it.


Answer



The problem seems to be you are executing the script before the element is loaded.



I assume this script is added in the hello.js file which is added before the DOM is created.



The solution here is to execute the script after the DOM is ready like:



window.onload = function(){
document.getElementById("subm").onclick=function(){

alert("Hello WOrld");
}
}


All JavaScript code which deals with DOM elements like the one above has to be executed only after the DOM is loaded.



Demo: Fiddle


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...