View Full Version : Resolved Why Error console tells me :exp is null?

01-16-2012, 03:31 PM

Error Console tells me : exp is null Line 10

This does not make any sense to me. Could someone look at the short script below and tell me why I get this message?

I know how to make this script work, but I just want to understand why function changePar cannot access the variable exp in the script below.
Thank you very much.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
<html xmlns="http://www.w3.org/1999/xhtml">
<title> Exercise 2</title>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />

<script type="text/javascript">

function changePar() {
exp.getElementsByTagName("button")[0].onclick=function() {
document.getElementById("changingParagraph").innerHTML="Hello World";



<div id="experiment">
<button>Click Here</button>

<p id="changingParagraph"></p>


01-16-2012, 03:32 PM
Because the element you are trying to access doesn't exist until after the page loads.

01-16-2012, 03:36 PM
Because the element you are trying to access doesn't exist until after the page loads.

I know, when I define the function , the variable does not exist.

But when I call the function with <code>window.onload</code>, it does.

Does it mean, that when I define the function, all variables that I use inside it, should already exist?

01-16-2012, 03:41 PM
Kind of right. Your variable is declared as a global. Javascript will try to get that element before the page is finished loading. It will fail because it doesn't exist until the DOM is completed loaded so yes if you plan on getting elements from the DOM you need to wait until the page is fully loaded until you try to access them.

Philip M
01-16-2012, 03:46 PM
Change to this:-

<script type="text/javascript">

function changePar() {
var exp=document.getElementById("experiment");

01-16-2012, 04:00 PM
Thank you!

01-17-2012, 08:48 AM
Just to clarify what your problem was.

When you ran the statement:


it set exp to null because that id didn't exist in the page at that time.

That's one of the many reasons why you should put your JavaScript immediately before the </body> tag so that the HTML loads first and all the ids will therefore exist when you try to reference them.