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?