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

95
Visualizações
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 à 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