SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Enthusiast
    Join Date
    Jul 2005
    Posts
    70
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    getElementById problem

    I'm reading the SitePoint book "Simply Javascript." On page 69 there is an example of how to use getElementById to find the tag name of a node you are referencing. But I can't seem to get this simple code to work. Here's the JavaScript I'm using:

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

    if (target != null) {
    alert(target.nodeName);
    } else {
    alert("this isn't working");
    }

    And here's the HTML code:

    <body>
    <a id="berenger" href="http://www.castaway.com">Tom Berenger</a>.
    </body>

    The alert always says "this isn't working." I don't understand why. It seems very straightforward and simple. What am I doing wrong. Thanks for any help.

  2. #2
    SitePoint Author silver trophybronze trophy

    Join Date
    Nov 2004
    Location
    Ankh-Morpork
    Posts
    12,158
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Where is your JavaScript code in relation to the HTML?

    If you have that snippet of JavaScript in the <head>, it won't work. JavaScript is executed where it appears, so the code will run before there is an element with id="berenger" in the document.

    If you put the JavaScript code just before the </body> tag it should work.
    Birnam wood is come to Dunsinane

  3. #3
    SitePoint Enthusiast
    Join Date
    Jul 2005
    Posts
    70
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ah, OK, that makes sense. I don't remember reading about that in the book so far, but maybe I missed it. I was actually using an external .js file, but I was referencing it in the <head>. Thank you!

  4. #4
    SitePoint Author silver trophybronze trophy

    Join Date
    Nov 2004
    Location
    Ankh-Morpork
    Posts
    12,158
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You're welcome. It's a mistake that everyone has to make at one time or another, I think.
    Birnam wood is come to Dunsinane


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •