0

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");
}
Community
  • 1
  • 1
user1787489
  • 767
  • 2
  • 7
  • 14

2 Answers2

3

You have to put the JavaScript at the bottom of the page, otherwise the par1 element won't be available when your code runs:

<head>
    <title>Positioning and flow tests</title>
</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>
    <script type="text/javascript" src="Positioning and flow tests.js"></script>
</body>

An alternative to this, is to set your code to run when the page has finished loading:

var var1;
window.onload = function () {
    var1 = document.getElementById("par1");
};

function f1()
{
    alert(var1.innerHTML);
}

function f2()
{
    alert("batman");
}

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.

Joseph Silber
  • 193,614
  • 53
  • 339
  • 276
1

You need to either put the code after the element or do this: HTML:

<body onload="init()">
...

JS:

var var1;
function init() {
    var1 = document.getElementById("par1");
}

function f1()
{
    alert(var1.innerHTML);
}

The problem is you are trying to get an element that has yet to be created and therefore doesn't exist. Using an 'init' function will wait until the entire document has loaded before trying to get the elements.

James Coyle
  • 8,191
  • 1
  • 32
  • 46