mercredi 27 juillet 2016

Uncaught TypeError: Cannot read property 'innerHTML' of null error

I am refreshing display of time after every 1 seconds. I try to prefix that display with text from element divMessage. However, I keep getting the error "Uncaught TypeError: Cannot read property 'innerHTML' of null" error. However, the text of divMessage was assigned without any problems in the document ready function ($function()). So, what is going on here?

<script src="http://ift.tt/1XwG72U"></script>
<script type="text/javascript">
    var myVar = setInterval(myTimer, 1000);
    var loaded = false

    $(function(){
            // Set divMessage text here (I see no errors here)!
            loaded = true
        });
    });

    function myTimer() 
    {
        var d = new Date()
        var dateTime = d.toLocalTimeString()
        var divMessage = ''
        if (loaded)
            // Uncaught TypeError: Cannot read property 'innerHTML' of null" error here!
            divMessage = document.getElementById("divMessage").innerHTML
        document.getElementById("div2").innerHTML = "<span style=\"color:green\">" + 
           divMessage + ", " + dateTime + "</span>";
    }
</script>
</head> 

The elements are defined like this.

<div id="divMessage"><span style="color:yellow">some text</span></div>
<div id="div2"><span style="color:yellow">some text</span></div>




Aucun commentaire:

Enregistrer un commentaire