-1

I am having a problem with my JavaScript, when I put it into JSFiddle it works fine. But it wont work locally? Here is the fiddle: http://jsfiddle.net/4Ukkz/

var String = "preacher preacher, 5th grade teacher";
document.getElementById('text').innerHTML=String;

So the problem is. In the JSFiddle, the text will display, But locally nothing will display. Note. It works in the fiddle. but not on my computer

2
  • You are trying to manipulate the DOM before it's ready. The fiddle runs the js using the onLoad event. Commented Jan 26, 2014 at 5:30
  • As someone had pointed out (seems like they deleted their answer), creating a variable called "String" is bad form. String is a global object/constructor provided in JavaScript, by re-defining it, you can run into a lot of trouble if someone else tries to use the global String in the same scope. I guess the tl;dr; is do not use a variable called "String", call it something else. Commented Jan 26, 2014 at 5:42

2 Answers 2

2

In JSFiddle, your code is automatically wrapped with

window.onload = function() {
    // your code
};

This is necessary because in your code, script.js is included above <div id="text"></div>. If you don't wait until that element exists, document.getElementById('text') will return null and the attempt to set innerHTML will fail.

The solution is to wrap your code as above or move your script tag below the div.

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

Comments

1

May be you don't have a script.js file with the javascript code you pasted in the fiddle?

And move the script element after your body. So your JavaScript code runs after all the elements in the body have been created.

So something like this:

<html>
<title>hi</title>
<head>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div id="text"></div>
</body>
<script type='text/javascript' src='script.js'></script>
</html>

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.