Trying to create a JavaScript function that changes the innerHTML of a paragraph within an xmlHttp.onreadystatechange function, I encountered an error in the Chrome Console:
Uncaught TypeError: Cannot set property 'innerHTML' of null
at XMLHttpRequest.xmlHttp.onreadystatechange (myfile.html:20)
at myfile.html:25
Interestingly, despite the error message, the innerHTML is still changed. The odd thing is that the error only appears when attempting to change two elements.
An observation made was that if one of the "document.getElementById" lines is commented out, everything works fine.
Any ideas on what might be causing this issue would be highly appreciated!
Below is the complete HTML Code:
var url = "https://google.com"; // modified URL
var xmlHttp = new XMLHttpRequest();
// create XMLHttpRequest object
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
// works only when either line below is removed
document.getElementById('id_hello1').innerHTML = "hello1";
document.getElementById('id_hello2').innerHTML = "hello2";
};
// open URL
xmlHttp.open("GET", url, true);
// send request
xmlHttp.send();
<h1>Hello1</h1>
<p id="id_hello1">loading...</p>
<h1>Hello2</h1>
<p id="id_hello2">loading...</p>