var mainUrl = "http://127.0.0.1:8000/";
var ajaxHot = document.getElementById("hotajax");
var ajaxPopular = document.getElementById("popularajax");
var ajaxToday = document.getElementById("todayajax");
var ajaxCurrent = document.getElementById("partial-index");
var ajaxIndex = document.getElementById("ajax-index");
function retrieveAjaxContent(ajaxButton, endpoint) {
ajaxButton.addEventListener("click", function () {
var request = new XMLHttpRequest();
var parser = new DOMParser();
request.open("GET", mainUrl + endpoint);
request.onload = function () {
var responseString = request.responseText;
var responseDocument = parser.parseFromString(responseString, "text/html");
var contentToAppend = responseDocument.getElementById("content-body").children[1];
ajaxCurrent.children[0].children[0].innerHTML = responseDocument.getElementById("content-body").children[0].innerHTML;
while (ajaxIndex.hasChildNodes()) {
ajaxIndex.removeChild(ajaxIndex.lastChild)
}
console.log(contentToAppend.childElementCount);
for(i=0; i<contentToAppend.childElementCount; i++) {
ajaxIndex.append(contentToAppend.children[i])
}
};
request.send();
});
}
retrieveAjaxContent(ajaxHot, "titles/hot/");
retrieveAjaxContent(ajaxPopular, "titles/popular/");
retrieveAjaxContent(ajaxToday, "titles/today/");
I am attempting to fetch elements from a URL and insert them into the ajaxIndex element, but I am encountering unexpected behavior.
---> The while statement is removing all child elements.
---> The console log outputs the total number of new titles which should be either 25 (for hot and today) or 4 (for popular).
---> However, the next statement only appends half of the expected titles, such as 13 out of 25 or 2 out of 4.
If I slightly modify the code like this:
for(i=0; i<contentToAppend.childElementCount; i++) {
console.log(contentToAppend.children[i])
}
It correctly logs all 25 (or 4 for popular) titles from the new page. But when I try to append them:
for(i=0; i<contentToAppend.childElementCount; i++) {
console.log(contentToAppend.children[i]);
ajaxIndex.append(contentToAppend.children[i]);
}
The result is that it both appends and logs only 13 (or 2 for popular) new elements.
I have even manually set the loop count to i<25, yet it still only appends 13 elements and adds "undefined" text to the HTML.
My question is twofold: why is this happening, and how can I go about fixing it?