SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Member
    Join Date
    Sep 2007
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    return null by getElementById

    Can anybody explain why getElementById always return null in this case? Am I doing anything wrong here in the code? I have posted the code below for your reference. I use Mozilla Firefox to view the following code.

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>Exercise 2 - Document Access</title>
    <script type="text/javascript">
    var myID = document.getElementById("mark");
    document.write(myID);
    </script>
    </head>

    <body>
    <p id="mark">This is a paragraph.</p>
    <ul>This is an unorder list.
    <li>Step one.</li>
    <li>Step two</li>
    <li>Step three.</li>
    </ul>
    </body>
    </html>

  2. #2
    CSS & JS/DOM Adept bronze trophy
    Join Date
    Mar 2005
    Location
    USA
    Posts
    5,482
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You're trying to access the element before it has been loaded.

    People usually use window.onload handlers to call functions containing DOM scripting.
    We miss you, Dan Schulz.
    Learn CSS. | X/HTML Validator | CSS validator
    Dynamic Site Solutions
    Code for Firefox, Chrome, Safari, & Opera, then add fixes for IE, not vice versa.

  3. #3
    SitePoint Member
    Join Date
    Sep 2007
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks Kravvitz. Can you give me an example of window.onload handlers? Is it something like <body onload="getValueById()"> and then use my getElementById function inside the getValueById function?

    BTW, I am new to Javascript and would like to know what is the most popular IDE/editor for editing Javascript/CSS/HTML?

  4. #4
    CSS & JS/DOM Adept bronze trophy
    Join Date
    Mar 2005
    Location
    USA
    Posts
    5,482
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You're welcome

    It's best to avoid using inline event handlers whenever possible. I suggest you read up on Unobtrusive JavaScript and other JavaScript Best Practices.

    Here's an example of a basic onload handler.

    PSpad is a good editor. It's one of the ones I use. For other recommendations check out the Text Editors thread.
    We miss you, Dan Schulz.
    Learn CSS. | X/HTML Validator | CSS validator
    Dynamic Site Solutions
    Code for Firefox, Chrome, Safari, & Opera, then add fixes for IE, not vice versa.


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
  •