Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

139
Views
JavaScript DOM depth via recursion

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.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!