SitePoint Sponsor

User Tag List

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

    Keeping DOM seperate from html and css -- HELP!

    I am incredibly new to javascript, in fact I just started reading Simply Javascript yesterday. I'm learning about DOM and I can't seem to understand why a simple expression like this:

    Code:
    var koko = document.getElementById("koko");
    var kokoHref = koko.getAttribute("href");
    alert(kokoHref);
    relative to this html:

    Code:
    <body>
    
    
    
    <a id="koko" href="http://www.koko.org/">Let's all hug Koko</a>
    
    
    </body>
    </html>
    Can't be put in an external javascript file and referenced with a simple

    <script type="text/javascript" src="jscript.js"></script>

    in the head section.

    Instead to get this simple script to run properly it has to be placed at the bottom of the html just before the </body> tag. It just looks ugly to me, and all along in all the internet scripting I've done, I've always been told to keep the different scripts, that is html and css separate...but apparently javascript doesn't work like that?

    I'm so confused can somebody help please?

  2. #2
    SitePoint Guru
    Join Date
    Apr 2006
    Posts
    802
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    In the head, the elements defined in the body don't exist yet.

    There is no element with the id of 'koko' when you reference it.

    You can put the script element in the body, as a src reference, anywhere after 'koko' is introduced.

    Or you can write your code so that it is called after the page loads, from a <script src=url in the head:

    //(js file)
    Code:
    window.onload=function(){
      alert(document.getElementById("koko").href);
    }

  3. #3
    SitePoint Member
    Join Date
    May 2008
    Posts
    9
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Oh shoot thank you that makes soo much more sense!!


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
  •