I have a small script which grabs a file and outputs in Javascript. Then after that output i want to edit the innerHTML.
But its saying it cannot set it. “Uncaught TypeError: Cannot set property ‘innerHTML’ of null”
This is what i have:
function call_file(file,div_id){
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById(div_id).innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET",file,true);
xmlhttp.send();
}
call_file('test.php','main'); //main = div_id to display content in
document.getElementById('total').innerHTML = 'test';
My test.php has:
<div id="total"></div>
I’m wondering why it cannot set?
Your call to set the innerhtml of total is happening before the state change event which happens in async. You’d have to ensure your Ajax call had completed before modifying the dom based on predicted added markup.