Possible Duplicate:
Why does jQuery or a DOM method such as `getElementById` not find the element?
I’ve been trying to learn js, but im having trouble getting a very simple example to work and i cant seem to find what im doing wrong. From all i understand the below example should work. When i click on the second button, it calls the function f2 and outputs “batman” as an alert, so i know the javascript page is linked correctly. But when i click on the first button nothing happens.
HTML:
<head>
<script type="text/javascript" src="Positioning and flow tests.js"></script>
</head>
<body>
<p id="par1">Test</p>
<button onclick="f1()">Click me for par 1 content</button>
<button onclick="f2()">Click me for predefined text</button>
</body>
</html>
Javascript
// JavaScript Document
var var1 = document.getElementById("par1");
function f1()
{
alert(var1.innerHTML);
}
function f2()
{
alert("batman");
}
You have to put the JavaScript at the bottom of the page, otherwise the
par1element won’t be available when your code runs:An alternative to this, is to set your code to run when the page has finished loading:
but this will wait until the page has completely loaded, which includes downloading all the images. If you were to click on the first button before all the images have been fully downloaded, you’d get an error.