Forum Moderators: open
The html page:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" 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" ></script>
</head>
<body>
<a id="koko" href="http://www.example.com/">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
The script is in the head-element (where it should be) but when it runs, the body-element doesn't exist yet, so your a-element doesn't exist yet. Hence, document.getElementById("...anything...") will always fail. What to do?
<head>...
<script type="text/javascript"><!--
function getKoko() {
var koko = document.getElementById("koko");
koko.setAttribute("href", "/GetKoko/");
koko.setAttribute("title", "Koko sets the title");
}
//--></script>
...</head>
<body>...
<a id="koko" href="http://www.example.com/" onclick="getKoko()">Get KOKO!</a>
...</body>
[edited by: MarkFilipak at 1:10 am (utc) on Mar. 9, 2008]
window.onload = function () {
var koko = document.getElementById("koko");
koko.setAttribute("href", "/GetKoko/");
koko.setAttribute("title", "Koko sets the title");
};
Not sure why yours isn't working, a test is pasted below that does work.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<!-- doctype all on one line!-->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Untitled</title>
<script type="text/javascript">
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="http://www.example.com/">Get KOKO!</a>
</body>
</html>