Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

147
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda