Sunday, 29 April 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

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...