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

94
Views
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
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!