neiler45
neiler45

Reputation: 3

can someone explain to me why i get an Uncaught TypeError: cannot set property of null

(function() {
        var myFunc = {
             init : function() {
                alert("I need");
                document.getElementById("myDiv").innerHTML = "help";
            }
        };
window.myFunc = myFunc;
})();
myFunc.init();

The alert() message works but the Uncaught TypeError is thrown when it reaches the next line. Can anyone explain to me why and how to fix it? I assume it is something to do with the scoping of the function as it will work if nested within the myDiv rather than the linked .js file.

Thanks

Upvotes: 0

Views: 5483

Answers (2)

SLaks
SLaks

Reputation: 887453

Your script is executing before the document is parsed.

You should move the <script> tag to the bottom of the document, or call init in the onload event.

Upvotes: 5

John Boker
John Boker

Reputation: 83709

is document.getElementById("myDiv") returning null?

Upvotes: 0

Related Questions