4

I have this simple HTML file:

<!DOCTYPE html>
<html>
<head>
    <script src='test.js'></script>
</head>

<body>
    <p>I am a paragraph tag</p>
    <h1 >I am an h1 tag</h1>
    <div id="id"> I am a div tag</div>
</body>

And this simple script (test.js):

y=document.getElementById("id");
y.style.color="green";

Why on earth is "y" null? The error I'm getting is

TypeError: y is null

I'm sure this is a simple syntax thing that I'm missing, but I can't for the life of me figure it out! Help!

Post Script: Both the html file and the test.js file are in the same folder.

  • This question gets asked several times a day. In the future, try researching the question before asking :) – 4castle Jun 15 '16 at 22:32
  • You should declare your variables using the var syntax, e.g. var y = document ..." Last, your javascript is running before the element has been loaded into the dom. You may be able to fix it by wrapping your javascript in (function() { }); – zeros-and-ones Jun 15 '16 at 22:44
  • @zeros-and-ones that makes it a local variable –  Jun 16 '16 at 02:28
  • Ah yes, local vs global. Here is a good short reference to JS variable scope: http://stackoverflow.com/questions/19721313/javascript-local-and-global-variable-confusion – zeros-and-ones Jun 16 '16 at 16:27

2 Answers2

7

you have to place the script at the end of the document when all the elements are created:

<!DOCTYPE html>
<html>
<head>

</head>

<body>
    <p>I am a paragraph tag</p>
    <h1 >I am an h1 tag</h1>
    <div id="id"> I am a div tag</div>
</body>
<script src='test.js'></script>
CMPS
  • 7,505
  • 4
  • 26
  • 49
  • Hmmm... that's weird. It works, but I've never had to do it before. I guess that's cause in everything else I've had it with an event handler so it doesn't run as soon as the document loads. –  Jun 15 '16 at 22:26
  • Correct, if you want to put it at the top you can use `window.onload` – CMPS Jun 15 '16 at 22:26
4

You can wrap the content on your script using $(document).ready if you are using jQuery or window.onload if using plain javascript.

Hector Barbossa
  • 5,190
  • 13
  • 45
  • 69
  • 1
    I don't think OP is using [tag:jQuery] – andlrc Jun 15 '16 at 22:26
  • 1
    @Hector Barbossa this is the SINGULAR LARGS+EST PROBLEM with Stackoverflow,, is people like you who decide, "drop it and try jQuery!" If the question is *not tagged jQuery* then *don't answer with jQuery*. –  Jun 15 '16 at 22:33
  • Sorry, my bad .. I didn't check the tags earlier, but I have given a plain javascript solution as well – Hector Barbossa Jun 15 '16 at 22:36