I recently attempted an exercise from the MDN website that involved using JSON to extract data and display it on a webpage. The code seems to be functioning correctly, generating the desired strings. However, I encountered an issue where the generated strings were not being assigned to the textContent properties of newly created paragraphs. Interestingly, when I manually performed the assignment in the console, it worked flawlessly.
"""
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<section>
</section>
<script>
const section = document.querySelector('section');
let requestURL = "https://raw.githubusercontent.com/mdn/learning-area/master/javascript/oojs/tasks/json/sample.json";
let request = new XMLHttpRequest();
request.open("GET", requestURL);
request.responseType = "json";
request.send();
let kittenInfo;
let motherInfo = "The mothers are";
request.onload = function() {
let catString = request.response;
extractInfo(catString);
}
function extractInfo(info){
let end = ", ";;
let total = 0;
let male = 0;
let names = "";
for (let i = 0; i < info.length; i++) {
if (i === info.length - 2) {
end = " and";
}else if (i === info.length - 1){
end = ".";
}
motherInfo += " " + info[i].color + " " + info[i].breed + " " + info[i].name + end;
for (let j = 0; j < info[i].kittens.length; j++) {
end = ",";
if (i === info.length - 1) {
if (j === info[i].kittens.length - 2){
end = " and";
}else if (j === info[i].kittens.length - 1){
end = ".";
}
}
if (info[i].kittens[j].gender === "m"){
male += 1;
}
names += " " + info[i].kittens[j].name + end;
total += 1;
}
}
kittenInfo = `There are ${total} kittens, ${male} of them are male and ${total - male} of them are female. ` +
`Their names are ${names}`;
}
let para1 = document.createElement("p");
let para2 = document.createElement("p");
para1.textContent = motherInfo;
para2.textContent = kittenInfo;
section.appendChild(para1);
section.appendChild(para2);
</script>
</body>
</html>