Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

141
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda