SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Enthusiast
    Join Date
    Jun 2008
    Posts
    49
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Question document.getElementById

    Hello,

    I'd like to ask you, why doesn't this work:

    <html>
    <head>
    <title>getElementById example</title>

    <script type="text/javascript">

    var target = document.getElementById("para1");
    alert(target.nodeName);

    </script>
    </head>

    <body>
    <p id="para1">Some text here</p>
    </body>
    </html>

    It says that "target is null". But I don't know why. Can anyone help? Thanks.
    Last edited by jake.polak; Jun 30, 2008 at 06:12.

  2. #2
    dooby dooby doo silver trophybronze trophy
    spikeZ's Avatar
    Join Date
    Aug 2004
    Location
    Manchester UK
    Posts
    13,807
    Mentioned
    158 Post(s)
    Tagged
    3 Thread(s)
    It's because the element you are referencing hasnt been created when you call for it.

    Code:
    <html>
    <head>
    <title>getElementById example</title>
    
    </head>
    
    <body>
    <div id="para1">Some text here</div>
    
    <script type="text/javascript">
    
    	var target = document.getElementById("para1");
    	alert(target.nodeName); 
    
    
    </script>
    </body>
    </html>
    Mike Swiffin - Community Team Advisor
    Only a woman can read between the lines of a one word answer.....

  3. #3
    d^_^b Iain G's Avatar
    Join Date
    Nov 2005
    Location
    Gloucester, UK
    Posts
    262
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    If you want to keep the script in the head of your HTML page then you can wrap the code in a function assigned to the onload event handler of the window:

    Code:
    <html>
    <head>
    <title>getElementById example</title>
    <script type="text/javascript">
    window.onload = function()
    {
    	var target = document.getElementById("para1");
    	alert(target.nodeName); 
    }
    </script>
    </head>
    
    <body>
    <div id="para1">Some text here</div>
    </body>
    </html>
    This means the code is only executed after the page has finished loading and the element with the ID will have been created.
    Coding and design philosophy:
    Keep It Simple, Stoopid


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
  •