Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

getElementById var is empty

Status
Not open for further replies.

wadesmart

Technical User
Feb 6, 2007
2
US
Im purchased Simply Javascript from Sitepoint and Im working on some
of these tutorials and none of them are working. I do not understand
what is wrong.

The html page:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
" <html xmlns=" lang="en-US">
<head>
<title>Get Tag By ID</title>
<meta http-equiv="Content-Type" content="text/html;
charset=utf-8" />
<link rel="stylesheet" type="text/css" href="pg84.css" />
<script type="text/javascript" src="pg84.js" />
</head>

<body>
<a id="koko" href=" all get KOKO!</a>
</body>
</html>

And here is the script:
var koko = document.getElementById("koko");
koko.setAttribute("href", "/GetKoko/");
koko.setAttribute("title", "Koko sets the title");

And the error is:
koko has no properties
line1: koko.setAttribute("href","/GetKoko/");

I have also tried:
koko.href = '/GetKoko/'
koko.title = 'Koko sets the title';

Im using Firefox 2.0.0.12 using Firebug 1.05 extension.

Wade
 
Hey, what is happening is your Javascript is parsing before the actual koko element is attached to the DOM. In other words, your trying to get properties to something that doesn't exist yet. Here is a quick rewrite of your program.
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "[URL unfurl="true"]http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">[/URL]
  <html xmlns="[URL unfurl="true"]http://www.w3.org/1999/xhtml"[/URL] lang="en-US">
    <head>
      <title>Get Tag By ID</title>
        <meta http-equiv="Content-Type" content="text/html;
charset=utf-8" />
        <link rel="stylesheet" type="text/css" href="pg84.css" />
        <script>
      window.onload = function() {
         var koko = document.getElementById("koko");
         koko.setAttribute("href", "/GetKoko/");
         koko.setAttribute("title", "Koko sets the title");
      }
      </script>
    </head>

    <body>
      <a id="koko" href="[URL unfurl="true"]http://www.koko.com/">Lets[/URL] all get KOKO!</a>
    </body>
  </html>
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top