Tom Abbott Tom Abbott - 13 days ago 6
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
myXhr.open("get", "index.json", true);

//makes the request
myXhr.send(null);

<!doctype html>
<html>
<head>
<title>My Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css">
<script src="https://code.jquery.com/jquery-1.8.2.min.js"></script>
<script src="https://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>

</head>
<body>
<div data-role="page">

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

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

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

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





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

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'>