nodeName Problem

Hello,

I’m reading Simply JavaScript and I ran into a problem with an example from a book. I can’t get nodeName to work properly. Am I doing something wrong?

Here’s my code:


<body>
  <h4 id="movieTitle">Analyze This</h4>

  <p>
    The film stars Robert De Niro as a mafioso and Billy Crystal as a psychiatrist.
  </p>
</body>


var target = document.getElementById("movieTitle");

alert(target.nodeName);

Help me, please. Thank you in advance.

Hi AverageMax, welcome to the forums,

Just guessing. Is the javascript running before the page’s DOM loads in?

I don’t know. I’m just starting with JavaScript. How can I check that? :blush:

Thank you. :slight_smile:

Well, there are a few ways things can be done.

If the javascript is in the <head> and isn’t in a function that’s called by onload (preferrably by adding an event listener to the body IMHO) or at the end of the page then the script runs before the page’s DOM is loaded in so the tags won’t be there yet to get. eg. this won’t work:

<html><head><title>nodeName test</title>
<script type='text/javascript'>
var target = document.getElementById("movieTitle");
alert(target.nodeName);
</script>
</head>
<body>
  <h4 id="movieTitle">Analyze This</h4>
  <p>
    The film stars Robert De Niro as a mafioso and Billy Crystal as a psychiatrist.
  </p>
</body></html>

but this will:

<html><head><title>nodeName test</title>
</head>
<body>
  <h4 id="movieTitle">Analyze This</h4>
  <p>
    The film stars Robert De Niro as a mafioso and Billy Crystal as a psychiatrist.
  </p>
<script type='text/javascript'>
var target = document.getElementById("movieTitle");
alert(target.nodeName);
</script>
</body></html>

*a quick and dirty example, but hopefully it helps

My JavaScript is in an external file, but this works!

Thank you very much!

I agree, putting your script at the bottom is the best technique to speed up your web page and improve your ability to work with the DOM.

The Simply Scripting book uses its own custom library called Core, which includes a method called .start()
Pages 58 and 59 of the book cover that, in the section titled Unobtrusive Scripting in the Real World.

I must have missed it.

Thanks.