When using JavaScript to create table cells and rows and populate them with information from a JSON file, I encounter an issue where the unique ids assigned to the table cells in my code are undefined. This causes problems when trying to reference these ids later on as they appear to be "blank".
I'm puzzled by why this error is occurring as the table is being created and everything seems to display correctly. Below you will find my code along with additional relevant details, please note that I am not using jQuery for this implementation.
HTML:
<div id="info">
<table id="country">
</table>
</div>
JavaScript:
document.getElementById("country").innerHTML = "";
for (var i = 0; i < jsonData.api.countries.length; i = i + 2) {
document.getElementById("country").innerHTML += "<tr><td id='" + jsonData.api.countries[i].code + "'>" + "<img src=" + jsonData.api.countries[i].flag + ">" + "<p>" + jsonData.api.countries[i].country + "</p>" + "</td>" +
"<td id='" + jsonData.api.countries[i + 1].code + "'>" + "<img src=" + jsonData.api.countries[i + 1].flag + ">" + "<p>" + jsonData.api.countries[i + 1].country + "</p>" + "</td>"
+"</tr>";
}
An error message appears in the console log:
Uncaught TypeError: Cannot read property 'code' of undefined
at XMLHttpRequest.myfunction
Below is a screenshot showing how the HTML appears in the page elements:
https://i.sstatic.net/q4Xq5.png
Here is a snippet of the JSON file used: