javascript – Uncaught Typeerror: cannot read property innerHTML of null

javascript – Uncaught Typeerror: cannot read property innerHTML of null

var idPost=document.getElementById(status).innerHTML;

The status element does not exist in your webpage.

So document.getElementById(status) return null. While you can not use innerHTML property of NULL.

You should add a condition like this:

if(document.getElementById(status) != null){
    var idPost=document.getElementById(status).innerHTML;
}

Update:

The question doesnt ask for jquery. So lets do it without jquery:

document.addEventListener(DOMContentLoaded, function(event) { 
    //Do work
});

Note this method will not work on IE8.

Old Answer:

You are calling this script before DOM is ready. If you write this code into jquerys $(function() method it will work.

javascript – Uncaught Typeerror: cannot read property innerHTML of null

If the script is in the head of your HTML document, the body of your HTML document has not yet been created by the browser, regardless of what will eventually be there (the same result occurs if your script is in the HTML file but above the element). When your variable tries to find document.getElementById(status) it does not yet exist, and so it returns a value of null. When you then use the variable later in your code, the initial value (null) is used and not the current one, because nothing has updated the variable.

I didnt want to move my script link out of the HTML head, so instead I did this in my JS file:

var idPost //define a global variable
function updateVariables(){
    idPost = document.getElementById(status).innerHTML; //update the global variable
}

And this in the HTML file:

<body onload=updateVariables()>

If you already have an onload function in place, you can just add the additional line to it or call the function.

If you dont want the variable to be global, define it locally in the function that you are trying to run and make sure the function is not called before the page has fully loaded.

Leave a Reply

Your email address will not be published.