0

I'm trying to write text chosen from a set of random strings inline with text in the html body. Here is my code so far:

Javascript

var textArray = [
    'STRING 1',
    'STRING 2',
    'STRING 3',
    'STRING 4',
    'STRING 5',
    'STRING 6'];
var randomNumber = Math.floor(Math.random() * textArray.length);
document.getElementById('output').innerHTML = (textArray[randomNumber]);

HTML

<body>
TEXT <span id="output"></span> TEXT
</body>

It works in JSFiddle, but I get an error in browser "Uncaught TypeError: Cannot set property 'innerHTML' of null." What's wrong with this? Also, is there a more efficient way of doing this? Here is the JSFiddle.

1
  • Check if DOM is already loaded and if you have any typo in the id Commented May 28, 2014 at 14:35

2 Answers 2

2

It sounds like the JavaScript code is running before the DOM has been fully loaded, so there is no element with id output available.

Try running your JS code from inside the document.onload handler and it should work.

Sign up to request clarification or add additional context in comments.

2 Comments

You're absolutely right! I missed the "onLoad" setting in JSFiddle. When I set it to "No Wrap - in <head>" the code breaks. Now, I'm not sure how to use the document.onload in conjunction with my current code. I'm very new to JS. What's the right syntax?
I wouldn't use onload, personally. Try putting your <script>'s at the very end of the body tag instead.
0

You must add ready state and include jQuery.

$(function(){
   /*code here...*/
}

Try this

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.