0

I have a window.onload function right before a self invoking function.

window.onload = function(){
console.log(document.getElementById("one")); //returns null
}

(function selfExecuting(){
    console.log("hi")
}());

The HTML is simply:

<div id="one">hi</div>

When I try to find a DOM element in the window.onload function, it's returning "null". UNLESS I add a line of code which stores an unused variable.

window.onload = function(){
console.log(document.getElementById("one")); //now, this returns "<div id="one">hi</div>"
}

var unusedVar = "var"; // This unused variable makes the code work

(function selfExecuting(){
    console.log("hi")
}());

Can someone help me understand why it's working like this? What is this unused line of code doing? I have a feeling this has something to do with how self invoking functions work, but I'm not sure.

A note: I tried to share this as a fiddle, but it resulted in slightly different console logs. The console logs I'm getting are with Chrome if that makes a difference.

0 Answers0