Uncaught TypeError: Cannot set property 'onclick' of null
As I see you are using the JQuery then use the jQuery's function why are you using javascript.
Here is the code for you desire:
$(document).ready(function(){
$("#subm").click(function(){
alert("Hello World");
});
});
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
It is probably happening because the script runs before the DOM loads.
Try putting the script in
window.onload = function() {
{your code}
}
window.onload() didn't solve my problem so i had to write code to wait for the element to get loaded. You can do something like this:
function waitForLoad(id, callback){
var timer = setInterval(function(){
if(document.getElementById(id)){
clearInterval(timer);
callback();
}
}, 100);
}
waitForLoad("subm", function(){
console.log("load successful, you can proceed!!");
document.getElementById("subm").onclick = function()
{
alert("I got clicked");
}
});