FrontendPro

21Implement getElementsByClassName() recursively

easyAbout 15 minutesCodingdomrecursiontrees

Problem

Implement getElementsByClassName(root, classNames) without using the built-in getElementsByClassName or querySelectorAll. Walk the DOM tree recursively and return an array of every descendant element of root that has all of the given classes.

// <div id="root">
//   <div class="card featured">…<span class="card"></span></div>
//   <p class="card"></p>
// </div>
getElementsByClassName(root, "card"); // [div.card.featured, span.card, p.card]
getElementsByClassName(root, "featured card"); // [div.card.featured]

Requirements

  • classNames may contain several names separated by spaces; an element must have all of them, in any order.
  • Match whole class names only: "item" does not match class="items".
  • Return elements in document order (depth-first, parent before children).
  • Do not include root itself.
  • An empty or blank classNames returns [].

Try it yourself

Write your solution, run it, then submit to check it against the tests.

App.jsxReact + DOM

Step-by-step

classNames.trim().split(/\s+/) turns " featured card " into ["featured", "card"]. If nothing is left, return [] straight away.

Unlock the full solution

What's inside

  • Step-by-step
  • Approach
  • Solution
  • Complexity
  • Edge cases
  • Follow-up questions
  • Tests

Includes 2 code listings, 5 edge cases, 4 follow-up questions.

One-time payment by UPI, card or net banking. Launch price.

All 150 answersOne payment, yours forever