0

Why do I get an error or " Uncaught type error: Cannot set property 'innerHTML' of null?". This is my code

function ajax()
 {
var pathxml;
var answer;
if (window.XMLHttpRequest) {
  pathxml = new XMLHttpRequest();
}
else
{
    pathxml = new ActiveXObject("Microsoft.XMLHTTP");
}

pathxml.onreadystatechange= function()
{
    if (pathxml.readyState==4 && pathxml.status==200) 
    {
         answer = pathxml.responseText;

    document.getElementById("ans").innerHTML = answer;

    }
 }
 pathxml.open("GET","books/ax",true);
 pathxml.send();
  }

4 Answers4

1

The element doesn't seem to exist or doesn't seem to match any known object - thats why NULL is returned.

Null expresses a lack of identification, indicating that a variable points to no object. In APIs, null is often retrieved in a place where an object can be expected but no object is relevant.

Seems to be a duplicate of this question..

I would recommend you debug 'ans' as mentioned here..

Another reason could be that you are running your code before the DOM is constructed. Try running your code in a window.onload handler function as mentioned in this post..

Here a link to the method and one link to the global object null..

Hope that helped..

iLuvLogix
  • 3,762
  • 18
  • 36
0

Probably the document.getELementById("ans") has no result. Debug that first.

Niels Steenbeek
  • 4,348
  • 2
  • 37
  • 50
0

Try this code:

document.getElementById("displayDiv").innerHTML = "EXPIRED";

<span id="displayDiv"></span>
Eric Aya
  • 68,765
  • 33
  • 165
  • 232
sameer
  • 397
  • 2
  • 9
  • 19
0

There are different possible cause as discussed would just like to add this for someone who might have the same issue as mine.

In my case I had a missing close div as shown below

   <!DOCTYPE HTML>
   <html>
   <head>
   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
   <title>Untitled Document</title>
   </head>
   <body>
   <div> //I am an open div
    <div id="hello"></div>
   <script type ="text/javascript">
       what();
       function what(){
          document.getElementById('hello').innerHTML = 'hi';
       };
   </script>
   </body>
   </html>

Missing a close div can result to disorganization of the transversal from child to parent or parent to child hence resulting to an error when you try to access an element in the DOM

you also might need to checkout this previous question there are a lot of different possible cause and how to fix them here :Cannot set property 'innerHTML' of null

Proxybee
  • 94
  • 1
  • 5