Uncaught Typeerror: cannot read property 'innerHTML' from null

Can someone explain what the thesis of errors is?

Uncaught TypeError: cannot read property 'innerHTML' from null

View on my website This is the line that causes the error:

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

thank

+5
source share
7 answers
var idPost=document.getElementById("status").innerHTML;

The 'status' element does not exist on your web page.

So document.getElementById ("status") returns null. Although you cannot use the innerHTML property for NULL.

You must add this condition:

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

Hope this answer helps you. :)

+21
source

Update:

jquery. jquery:

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

, IE8.

:

script, DOM . jquery $(function(), .

+17

, , , , HTML "status":

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

HTML-: , , , .

+4

html body

    <html>
    <body>
    <p>asdasd</p>
    <p>asdasd</p>
    <p>asdasd</p>
    <script src="myfile.js"></script>
    </body>
    </html>
+4

script HTML, HTML , , ( , script HTML, ). document.getElementById( "status" ), , null. , (null), , .

script HTML, JS :

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

HTML:

<body onload="updateVariables()">

onload, .

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

+3
source

I had a similar problem, but I had an existing id, and as egiray said, I called the DOM before loading, and the Javascript console showed the same error. So I tried:

window.onload = (function(){myfuncname()});

and he starts to work

+3
source
//Run with this HTML structure
<!DOCTYPE html>
<head>
    <title>OOJS</title>

</head>
<body>
    <div id="status">
    </div>
    <script type="text/javascript" src="scriptfile.js"></script>
</body>
</html>
0
source

All Articles