Can't Access DOM Within AJAX

Simplified version of the problem:


var test = document.getElementById("test");
alert(test.innerHTML) // alerts "hello world"

// ...

xmlhttp.onreadystatechange = function () {
	if (this.readyState === 4) {
		if (this.status === 200) {
			alert(test.innerHTML) // error: "cannot read property 'innerHTML' of null"
		}
	}
};

Is there some reason that an XMLHttpRequest’s readystatechange event handler wouldn’t have access to DOM elements? I tried it with literals, and that works:


var test = "hello world";

// ...

xmlhttp.onreadystatechange = function () {
	// ...
			alert(test) // alerts "hello world"
	// ...
};

It only fails when I’m trying to get at an element in the DOM, and when I’ve defined that element previously. This will also work:


xmlhttp.onreadystatechange = function () {
	if (this.readyState === 4) {
		if (this.status === 200) {
			test = document.getElementById("test");
			alert(test.innerHTML) // alerts "hello world"
		}
	}
};

So everything works, but I’m using the test element in other places. Is there some reason I need to redefine it here, or am I doing something wrong?

You were right: I over simplified. I had everything wrapped up in an anonymous function to prevent global variables. The last line, for housekeeping, was what kept screwing me up:


var1 = var2 = var3 = test = null;

By not setting test to null, it worked as it should have. :blush:

The first block should work, as long as it’s being executed after the DOM has loaded. Have you checked that? This means putting all that JS after the HTML element for “test”, or wrapping it all in some sort of onload event.

Or perhaps by simplifying it for posting here you’ve omitted where the problem lies. Are you sure test and the xmlhttp.onreadystatechange are defined in the same scope, or test is in a more outer scope?

It would help to see more complete code.