0

I am trying to understand why a piece of code that I wrote doesn't work. (FYI, this is for a class, but I have already completed the project successfully, and now I am just trying to understand why something didn't work.)

I need to generate a picture x number of times and then append all of the pictures to a div.

Here is the HTML.

<body>
  <div id="leftSide"></div>
  <div id="rightSide"></div>
</body>

Here is the Javascript.

<script>
  var theLeftSide = document.getElementById("leftSide");
  var myVariable = 5;

  function myFunction() {
    for (var i = 0; i < myVariable; i++) {
      var x = document.createElement("img");
      x.setAttribute("src", "myFile.png");
      x.style.top = Math.floor(Math.random() * 400) + "px";
      x.style.left = Math.floor(Math.random() * 400) + "px";
      theLeftSide.appendChild(x);
    }
  }
</script>

When I run the code, I receive a console message stating "Cannot read property 'appendChild' of null". When I move var theLeftSide inside the function, it works as expected.

I am new to JavaScript, but I thought that a variable declared outside a function using the var name = value; syntax would be considered global and therefore accessible inside a function?

I'm sure I am missing something but I'm not sure what.

Thanks!

user3822485
  • 55
  • 1
  • 8
  • Move your script into the end of `` or execute it in DOMReady callback. – raina77ow Oct 27 '15 at 21:03
  • 1
    You are running the script before the elements are placed in the DOM, therefore the script doesn't know what they are yet. – Spencer Wieczorek Oct 27 '15 at 21:04
  • BTW, `cannot read property of null` actually means the variable is in scope (as ReferenceError would have been thrown otherwise). Its value is `null`, result of getElementById not finding the corresponding element. – raina77ow Oct 27 '15 at 21:08

0 Answers0