Tom Abbott Tom Abbott - 1 year ago 101
HTML Question

Getting the error message: Uncaught TypeError: Cannot set property 'innerHTML' of null

I've come across this error message in the console of my browser "Uncaught TypeError: Cannot set property 'innerHTML' of null".

Does anyone know how to resolve this?

//create a new XMLHttpRequest object
var myXhr = new XMLHttpRequest();

//function will be called when the state of the request changes
myXhr.onreadystatechange = function () {
if (this.readyState === 4) {
if (this.status === 200) {
//single JSON
var film = JSON.parse(myXhr.responseText);
var output = "";
output += "<h1>" + film.title + "</h1>";
output += "<p>" + film.director + "</p>";
var contentDiv = document.getElementById("content");
contentDiv.innerHTML = output;
} else {
alert("Something went wrong.");

//specify the resource we want to access"get", "index.json", true);

//makes the request

<!doctype html>
<title>My Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="">
<script src=""></script>
<script src=""></script>

<div data-role="page">

<div data-role="header">
<h1>My Title</h1>
</div><!-- /header -->

<div data-role="content">
<p>Hello world</p>
<!-- /content -->

<div data-role="footer">
<h4>My Footer</h4>
</div><!-- /footer -->

</div><!-- /page -->
<script src="index.js"></script>

I've also made a JSON file with the below data:

"title": "Jaws",
"year": "1975",
"director": "Steven Spielberg"
"title": "Mean Streets",
"year": "1973",
"director": "Martin Scorcese"
"title": "Forrest Gump",
"year": "1994",
"director": "Robert Zemeckis"

Jai Jai
Answer Source

Because this content element does not exist in the DOM, so it results in null so what you can do is add the id attribute to your div:

<div data-role="content" id='content'>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download