Uncaught Typeerror: cannot read property 'innerHTML' of null

前端 未结 8 2160
遥遥无期
遥遥无期 2020-12-05 12:04

Can anyone explain what is theses errors?

Uncaught TypeError: cannot read property \'innerHTML\' of null

View on my website This

相关标签:
8条回答
  • 2020-12-05 12:34

    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 didn't 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 don't 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.

    0 讨论(0)
  • 2020-12-05 12:34

    Looks like the script executes before the DOM loads. Try loading the script asynchronously.

     <script src="yourcode.js" async></script>
    
    0 讨论(0)
  • 2020-12-05 12:42
    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;
    }
    

    Hope this answer can help you. :)

    0 讨论(0)
  • 2020-12-05 12:51
    //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 讨论(0)
  • 2020-12-05 12:55

    I had a similar problem, but I had the existing id, and as egiray said, I was calling DOM before it loaded and Javascript console was showing the same error, so I tried:

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

    and it starts working.

    0 讨论(0)
  • 2020-12-05 12:56

    run the code after your html structure in the body statement

        <html>
        <body>
        <p>asdasd</p>
        <p>asdasd</p>
        <p>asdasd</p>
        <script src="myfile.js"></script>
        </body>
        </html>
    
    0 讨论(0)
提交回复
热议问题