I've attempted multiple times to refactor this to use iteration instead of recursion but I just can't wrap my head around it. Maybe it has something to do with the recursion happening within a loop. Assistance, even just pseudo-code, would be extremely appreciated.
var getElementAndDescendants = function (el) {
var docFrag = document.createDocumentFragment();
var children = el.parentElement.querySelectorAll("tr[data-parentid='" + el.getAttribute("data-myid") + "']");
docFrag.appendChild(el);
var len = children.length;
for (var index = 0; index < len; index++) {
docFrag.appendChild(getElementAndDescendants(children[index]));
}
return docFrag;
};
Update: This is just a small piece of a larger function that attempts to sort a pseudo-tree in the DOM made out of TR's that have children TR's in the same table. Each of those children can have their own children. The solution ends up being a recursive function within which lies the recursive function you see here. Hence why I'm after the micro optimization (if there is any to be had). I tried to keep the question simple and thus removed the outer function.