SitePoint Sponsor

User Tag List

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

    DOM/Javascript: First Steps

    So I bought a copy of 'Simply Javascript' and I've slowly waded through the first couple of chapters, and arrive at the chapter on DOM. As with the previous chapters, I decided that the best way to learn would be to try out the example. Unfortunately, this doesn't seem to be going so well for the DOM stuff. I'm not sure whether it's the way I'm doing it or whether I'm trying something I shouldn't even be attempting to begin with, but I figured I should at least figure this out. So when I try to access a node in my html, let's say using document.getElementById, how do I confirm that my external javascript file actually accessed the node. And if it hasn't, what could be the problem? Here's how I've tried to test it (I've pasted my html markup bellow and the javscript code beneath it):

    <body>
    <p id="alpha">I hope this works this time.</p>
    </body>

    Here's the code in the .js file:

    var x = document.getElementById("alpha");
    alert(x);

    So I'm assuming that an alert box should appear upon opening the page saying, "I hope this works this time." But instead all I get is null. I've tried a number of things, but I'm not quite sure what the problem is.

    I'm sure the first person to read this will laugh at my quandary, but, please, I am unwashed as far as programming is concerned and would appreciate some help in overcoming this hurdle.

  2. #2
    Function Curry'er JimmyP's Avatar
    Join Date
    Aug 2007
    Location
    Brighton, UK
    Posts
    2,006
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    When a browser parses a document it will stop at each SCRIPT and will download then execute it before continuing parsing the rest of the document.

    I'm guessing you've placed the SCRIPT tag at the top of the document (probably in <head>?) so when the browser encounters your SCRIPT tag the <p> element does not yet exist. Try moving your SCRIPT tag somewhere below the paragraph.

    Code html4strict:
    <body>
        <p id="alpha">I hope this works this time.</p>
        <script src="some/file.js"></script>
    </body>
    James Padolsey
    末末末末末末末末末末末末末末末末末末末
    Awesome JavaScript Zoomer (demo here)
    'Ajaxy' - Ajax integration solution (demo here)


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
  •