Well, this is about DOM. I’m stuck on this page and I can’t move on.
I can’t get this code to work…I copied the exact same script and html. I embedded the script into the html like this and the body like this.
<script type="text/javascript">
var target = document.getElementById("berenger");
alert(target.nodeName)
</script>
<h1>
Sniper (1993)
</h1>
<p>
In this cinema masterpiece, <a id="berenger" href="/name/nm0000297/">Tom Berenger</a> plays a US soldier working in the Panamanian jungle.
</p>
when I try to preview it using Safari, Coda, Espresso, Firefox, the ALERT dialogue box doesn’t show. But in the book, it’s supposed to be popping out. please help. I’m using Mac.
I’ve also included an attachment for you to look at just to make sure if I did the right thing.
The problem is that the script is called before the html has loaded yet. If you put the script after the html is loaded, it works fine:
<h1>
Sniper (1993)
</h1>
<p>
In this cinema masterpiece, <a id="berenger" href="/name/nm0000297/">Tom Berenger</a> plays a US soldier working in the Panamanian jungle.
</p>
<script type="text/javascript">
var target = document.getElementById("berenger");
alert(target.nodeName);
</script>
The book certainly should make this a bit clearer.
To keep the script in the <head>, you could do this:
<script type="text/javascript">
function nameElement () {
var target = document.getElementById("berenger");
alert(target.nodeName);
}
window.onload = nameElement;
</script>
window.onload prevents the script from running until all the html has loaded.