DOM very basic question

Hi All!

Studying JavaScript first day here. HTML document code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "">
<html xmlns="">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="example.js"></script>
<h1 id="b">
Sniper (1993)
In this cinema masterpiece,
<a href="/name/nm0000297/">Tom Berenger</a> plays
a US soldier working in the Panamanian jungle.

example.js code, contained in the same folder as HTML file:

// JavaScript Document
var target = document.getElementById("b");

Just want to see the name of the element that matched the id specified in .getElementById method.
I don’t receive an alert box. JavaScript is enabled because I get the alert box when passing a simple string of text to alert function.

What am I doing wrong? I copied and pasted the code written in the book, still does NOT work.

The javascript is executed at the time you include the script, so the node is not there yet.
What you should do is something along the lines of

window.onload = function() {
  var target = document.getElementById("b");

In that the case the javascript will run when the whole document is loaded, which is what you want :slight_smile:

Thank you so so so much! I read about JavaScript being executed too fast before any html is loaded. thank you again!

alternatively you can put your script tag at the bottom of the code (after html closing tag), this way it will be executed after html doc is loaded as well. It is actually preferred to put your javascript code at the bottom as much as possible.

Yes, but just BEFORE the </body> tag, not AFTER the </html> tag. :wink:

yeah, you are right. But I just checked and it does work even if I put it after body and even after html tag. At least in FF and IE. Which is wrong of course :slight_smile:

Great piece of advice, thank you. I am going to try that out, but the only question I have is: I link to external .js file. Will it still work? As far as I know link files should be located in between of <head></head> tags? Please correct me if I am wrong?

Thank you.

Yep, it works even with the external file. Just put in before the closing body tag and everything works just fine!

Thank you so much for your help. I was pretty much upset yesterday. People writing this book should give this books to complete novices so that those can go through them and pin point of questions before they publish a book. Plus, this question of mine is pretty much the basics of JavaScript and for them it might be obvious… but once again, the book is written for beginners, not for pros.
Thank you for your help.

I agree with you there, one of the biggest barriers to JavaScript is understanding how browsers deal with javascript placed in different parts of an HTML document (as well as CSS and images). Any book dealing with JavaScript should ensure this is known before doing anything else.