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?

4
  • I just bought Jon Ducket's simplistic book on JavaScript. - I'd demand a refund Commented Jan 9, 2016 at 3:20
  • it looks nice, but it doesn't teach that well... Commented Jan 9, 2016 at 3: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 <script src= tag with in-line JS, to see if that was in fact the problem. Commented Jan 9, 2016 at 4:36
  • The book for the rest of us. Commented Jan 9, 2016 at 16:17

1 Answer 1

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> 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.