I am trying to display a series of posts and replies (a typical comment section) using a recursive function. I get it to print out the posts in the right order, but the replies seem to appear inside the comment that follows the one they refer to. In other words, the posts are not printed out on screen in the nested hierarchical order intended.
I tried the insertAfter() function suggested here but it makes no difference. Also tried lots of variations but there is just something I am missing. Or is this entirely the wrong approach to display nested posts? If so, any suggestions (links to) better ways? Thanks in advance!
var box = document.getElementById('commentBox');
function showThreads(sortedArr, respTo, parent = box){
//create two json-encoded arrays with post data
var selected = getResponsesTo(sortedArr, respTo)[0];
var remaining = getResponsesTo(sortedArr, respTo)[1];
//create new div element
var childDiv = document.createElement('div');
//append div at the end of last sibling [normal appendChild() doesn't work either]
parent.insertBefore(childDiv, parent.lastChild.nextSibling);
for(var i=0; i<selected.length; i++){
//get the json encoded element
var pi = selected[i];
//create new div element for post
var pDiv = document.createElement('div');
//add the post to the element, after formatting it in html with makePost function
pDiv.innerHTML = makePost(pi);
//add post to current division
childDiv.appendChild(pDiv);
//recursively get responses to that post if available
if(remaining.length>0){
showThreads(remaining, pi.pID, childDiv);
}else{
continue;
}
}
}