Studying JavaScript first day here. HTML document code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JavaScript</title>
<script type="text/javascript" src="example.js"></script>
</head>
<body>
<h1 id="b">
Sniper (1993)
</h1>
<p>
In this cinema masterpiece,
<a href="/name/nm0000297/">Tom Berenger</a> plays
a US soldier working in the Panamanian jungle.
</p>
</body>
</html>
example.js code, contained in the same folder as HTML file:
// JavaScript Document
var target = document.getElementById("b");
alert(target.nodeName);
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.
Thanks,
Alex.
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.
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
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?
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.