javascript – Uncaught TypeError: Cannot set property onclick of null

javascript – Uncaught TypeError: Cannot set property onclick of null

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

window.onload() didnt 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);
    }
});

javascript – Uncaught TypeError: Cannot set property onclick of null

As I see you are using the JQuery then use the jQuerys function why are you using javascript.

Here is the code for you desire:

$(document).ready(function(){
  $(#subm).click(function(){
      alert(Hello World);   
  });
});

Leave a Reply

Your email address will not be published.