0

So. I just bought Jon Ducket's simplistic book on JavaScript. Great read.

And I've been trying one of the first examplen, "Creating an Array." I'm pretty sure I did everything exactly as the book says, but it won't work. The element I'm trying to print within stays empty. Hear's my body:

<body>

<script type="text/javascript" src="Excersize1.js"></script>

<p id='colors'></p>

</body>

And hear's my JavaScript in that file.

var colors;

// array for colors
colors = ['white', 'black', 'custom'];

var el = document.getElementById('colors');

el.textContent = colors[0];

Any thoughts?

  • `I just bought Jon Ducket's simplistic book on JavaScript.` - I'd demand a refund – Jaromanda X Jan 09 '16 at 03:20
  • it looks nice, but it doesn't teach that well... – dandavis Jan 09 '16 at 03:53
  • I'm curious why you would have given this question a title of "External JavaScript". Besides the fact that that title does a horrible job of describing your question, I wonder why you thought this problem had to do with external JS at all. If you thought it did, it would have been quite easy to try replacing the ` –  Jan 09 '16 at 04:36
  • The book for the rest of us. – SuradMister Jan 09 '16 at 16:17

1 Answers1

0

It's because your javascript is being executed before the elements on your page is able load.

// Searches the DOM for an element with the ID 'colors'
// but will fail to find it because it hasn't been rendered yet
var el = document.getElementById('colors');

Try moving your javascript at the bottom of your page, so by the time it's run, the rest of your document will have loaded.

<body>
   <p id='colors'></p>

   <!-- Run the scripts last to help make sure the page is loaded first -->
   <script type="text/javascript" src="Excersize1.js"></script>
</body>
Nick Zuber
  • 4,769
  • 2
  • 19
  • 45