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

105
Vistas
Eloquent Javascript Chapter 14 Exercise 2 - Elements by Tag Name - Why Isn't Recursion Working?

In Chapter 14 of Eloquent Javascript (3rd Edition), the second exercise is to create a function byTagName that works like document.getElementsByTagName. The function should take a node and return all child elements with a given tag name.

My function should take a node and a tag name, then put each of the node's children in a holding array if the child matches the tag name. Then the function tries to concatenate the holding array with the result of calling itself recursively on each of the node's children. Finally, it returns the holding array.

My function isn't recursing correctly. Can anyone tell me why?

//THE FUNCTION THAT ISN'T WORKING:

function byTagName(node, tagName) {
  let elements = [];
  let tag = tagName.toUpperCase();
  for (let child of node.children) {
    if (tag == child.nodeName) {
      elements.push(child);
    }
    elements.concat(byTagName(child, tagName));
    //^This part isn't working. 
    //I think the recursive call to byTagName is returning nothing no matter what.
  }
  return elements;
}


console.log(byTagName(document.body, "h1").length);
// → Correctly logs "1"
console.log(byTagName(document.body, "span").length);
// → Should log 3, but logs "0"
let para = document.querySelector("p");
console.log(byTagName(para, "span").length);
// → Correctly logs "2"
<h1>Heading with a <span>span</span> element.</h1>
<p>A paragraph with <span>one</span>, <span>two</span> spans.
</p>

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