www.webdeveloper.com
Results 1 to 5 of 5

Thread: getElementById not working

  1. #1
    Join Date
    Nov 2006
    Posts
    198

    getElementById not working

    This seems like a total beginner thing, but I don't know why it isn't working. I'm working from examples from a sitepoint pdf. Here's my html:

    Code:
    <body>
    <h1 id="stupid">sdfasd</h1> 
    <p>sdjfa</p>
    <ul>
    <li>first</li>
    <li>second</li>
    <li>third</li>
    </ul>
    </body>
    and here's the script I have linked to in the header:

    Code:
    var target=document.getElementById("stupid");
    alert(target.nodeName);
    Shouldn't I get an alert that says "H1"?. I get nothing. Aargh! What am I doing wrong?

    When I run an if statement, I'll get an alert letting me know that the value of target is null, but why is it null? It should contain a reference to the h1 node.

    thanks...

  2. #2
    Join Date
    Mar 2009
    Posts
    485
    It should be 'alert(target.tagName)', not 'alert(target.nodeName)' . Look at this:

    Code:
    <html>
    <head>
    <script type ="text/javascript">
    function zzz(){
        var x = document.getElementById("stupid");
        alert(x.tagName);
    }
    
    window.onload = zzz;
    </script>
    </head>
    <body>
    <h1 id="stupid">sdfasd</h1> 
    <p>sdjfa</p>
    <ul>
    <li>first</li>
    <li>second</li>
    <li>third</li>
    </ul>
    
    
    </body>
    </html>

  3. #3
    Join Date
    Dec 2010
    Posts
    207
    There's nothing wrong with nodeName.

    When do you think that script runs?

  4. #4
    Join Date
    Mar 2009
    Posts
    485
    There's nothing wrong with nodeName.

    You are correct--unless you get a visitor running IE 5.5, in which case there can be problems. Nevertheless--the HTML page I showed does work and it does produce the output the original poster wanted to get.

  5. #5
    Join Date
    Aug 2007
    Posts
    3,767
    Your code is running before the page is created. Either put it in a function like Tcobb, or put the script after the element.
    Great wit and madness are near allied, and fine a line their bounds divide.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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



Recent Articles