I have a node with a bunch of child nodes which recurse. I'm trying to find out how far each node is from the root (which has an id of 'comment-0').
I have the following HTML structure:
<div id="comment-0">
<div id="comment-2598" class="comment comment--parent" data-cid="2598">
<div id="comment-2599" class="comment comment--child" data-cid="2599">
<div id="comment-2615" class="comment comment--child" data-cid="2615">
</div>
</div>
<div id="comment-2604" class="comment comment--child" data-cid="2604">
<div id="comment-2616" class="comment comment--child" data-cid="2616">
</div>
</div>
</div>
</div>
The calling function:
rootNode.querySelectorAll('.comment').forEach((el)=>{
const result = findDepth(el,0);
console.log("el: "+el.id, result);
});
and my recursive function:
const findDepth = (el, depth) => {
depth++;
console.log(el.id, el.parentNode.id);
console.log(depth);
if(el.parentNode.id !== 'comment-0'){
findDepth(el.parentNode, depth);
}else {
return depth;
}
};
The recursive function seems to successfully walk up to find out how far each node is from the root but, regardless the value of depth inside the function, when the value is returned it's undefined and I can't see why.