0

This seems like a pretty basic question, but I can't understand why this is happing. I am new to JavaScript.

When I have do something like this...

 <!-- variable defined but not used -->
 var theLeftSide = document.getElementById("leftSide");

 function generateFaces(){
    <!-- some code here -->
    document.getElementById("leftSide").appendChild(face);
 }

I have no problem, and the code runs. But when I instead use the variable I have declared, it no longer works because "theLeftSide is null".

This doesn't work...

 <!-- variable declared but not used -->
 var theLeftSide = document.getElementById("leftSide");

 function generateFaces(){
    <!-- some code here -->
    theLeftSide.appendChild(face);
 }

Why is this happening? I think I put all the relevant code, but I can add to it if need be.

L. Morrell
  • 45
  • 10
  • 1
    your first comment is _wrong_. The variable is defined, not declared. A declaration doesn't include assignment. – Ryan Jun 12 '16 at 16:33
  • You should wrap your code in `window.onload`. If the element is not rendered and you try to fetch it, it will return `undefined`. In my understanding, this is the issue – Rajesh Jun 12 '16 at 16:35
  • I looked at that question and it did not help me. It brings in a lot of things that I did not see as relevant. If you deem it relevant, please help me to understand it. – L. Morrell Jun 12 '16 at 16:38
  • @Rajesh I'm looking up window.onload now – L. Morrell Jun 12 '16 at 16:40
  • 1
    You are trying to access a dom element before it rendered. Try calling your code on `window.onload` or put your script at the end of html file – Rajesh Jun 12 '16 at 16:41
  • 1
    What are you talking about? How were these suggestions not helpful? Of course that's the problem. When the script loads in your browser, the element doesn't exist yet, therefore the value of `theLeftSide` is undefined. Put the script at the end of your html file and remove `async` attribute, if it has one. Or better, wrap it into `onload` or `DOMContentLoaded` event handler so it runs when the DOM is finished rendering. – Marko Gresak Jun 12 '16 at 16:42
  • @MarkoGrešak that comment was directed to a comment which has since been deleted by another user. – L. Morrell Jun 12 '16 at 16:45

1 Answers1

2

The problem is not the variable itself.

The assignment in the code is made before the DOM is ready.

Put your script tag at the end of the document body tag, and try.

Mario Santini
  • 2,905
  • 2
  • 20
  • 27
  • Thank you so much. This is my first use of DOM and the professor never went over that. I looked up the difference between declaring in head and body, and the pages that I saw didn't mention that. – L. Morrell Jun 12 '16 at 16:43