SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Member
    Join Date
    Dec 2008
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    New to Javascript, having trouble with Document Object Methods

    Greetings all, I am new to javascript, and the HTML DOM, and trying to learn it through the book 'Simply Javascript', by Kevin Yank & Cameron Adams. I am experienced with other scripting languages however, including PHP & ASP.

    Anyhow I am having trouble with the getElementById & getElementsByTagName examples in ch 3. eg.

    HTML Code:
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Untitled Document</title>
    <script type="text/javascript" src="example.js"></script>
    </head>
    
    <body>
    <ul>
    <li id="murray">Googol</li>
    <li>Yawho</li>
    </ul>
    </body>
    </html>
    Code:
    var target = document.getElementById("murray");
    alert(target.nodeName);
    Using HTML 4 strict doctype in the HTML page.Can't post that because it contains a link. =P
    In the firefox error console, this gives me the error, "target is null", and in IE6 I get the error "Object required". Similarly the following code:

    Code:
    var listItems = document.getElementsByTagName("li");
    var secondItem = listItems[1];
    alert(secondItem.nodeName);
    In firefox "secondItem is undefined", and IE6 "secondItem.nodeName is null or not an object.
    Can anyone please point out what i am doing wrong, because the code seems correct to me.

  2. #2
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    16,868
    Mentioned
    25 Post(s)
    Tagged
    1 Thread(s)
    The JavaScript is running before the page loads. Try moving the script tag to immediately before </body>
    Stephen J Chapman

    javascriptexample.net, Book Reviews, follow me on Twitter
    HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
    <input name="html5" type="text" required pattern="^$">

  3. #3
    SitePoint Member
    Join Date
    Dec 2008
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    yes, ur right, that was the problem. Thx


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
  •