1

I am just learning Javascript and need an answer to this question. Why doesn't this piece of javascript work in the HTML DOM using an internal script tag?

Here is my html doc. with an internal javascript extension:

<div id="targetarea">
    <p>Hello World</p>
</div>
<div id="target-area">
    <p id="tagline">Hello World!</p>
</div>
<script>
//Creating a a new element
// store the target area to a variable to keep things neat
var targetArea = document.getElementById("target-area");
// create our <p> element
var p = document.createElement("p");
// create a text node inside the <p>, note that we're 
//  using a variable "p" here
var snippet = document.createTextNode("this was a generated paragraph");
// insert our generated paragraph into the DOM
p.appendChild(snippet);
targetArea.appendChild(p);
</script>

This works fine internally but when use an external js file it does not. Can someone give me the right js snippet for this to work in an external file and explain why?

Calvin Edward
  • 21
  • 1
  • 6
  • what does your [js console](http://stackoverflow.com/questions/988363/how-can-i-debug-my-javascript-code) tell you? – Kaiido Dec 07 '14 at 14:28
  • when i entered it in the console it said: Uncaught TypeError: Cannot read property 'appendChild' of null – Calvin Edward Dec 07 '14 at 17:13
  • So this is because targetArea is null, your `document.getElementById("target-area")` failed. You might want to include your code into a [function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions), then call it on document's [`onload`](https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers.onload) event. This way, you're sure that the element is loaded before you call the function. If you still have the same error, check there is no typo in element's ids – Kaiido Dec 07 '14 at 18:06

2 Answers2

1

It depends when you're running the script.

If you load the script in the <head> section of the file the DOM of the page has not been loaded yet and therefore for example getElementById is going to fail.

Loading your external scripts as the last thing in the <body> part will solve this problem.

6502
  • 112,025
  • 15
  • 165
  • 265
0

If the code runs fine internally but not externally,the problem could be linking the JS file. Check your link to the JS file and make sure it is linked correctly. If you linked the javascript file like this

<script src="javascriptFile.js">
</script>

and the code still fails to run correctly, then the problem may lie elsewhere. Also make sure you are loading scripts inside of the body, and make sure the file path is correct.

You would be suprised how often small mistakes like typos cause problems like these.

Reuben Ward
  • 101
  • 1
  • 9
  • yes it is linked correctly.I made sure. Other javascript snippet within the same js file works fine except for this one. – Calvin Edward Dec 07 '14 at 14:06