Premium

DOM Tree Walk 2: Find Closest Ancestor

By FrontendAtlas Team · Updated Jan 31, 2026

Implement closestWithin(node, selector, boundary) for a DOM-like tree. This is a simplified .closest() used constantly in UI code (event delegation, component boundaries). Requirements: 1) Walk up using parentNode starting from node. 2) Return the first node that matches selector. 3) Do not walk above boundary…

What you’ll build / What this tests

This premium javascript coding focuses on DOM Tree Walk 2: Find Closest Ancestor. You’ll apply dom and tree thinking with intermediate level constraints. The prompt emphasizes Implement closestWithin(node, selector, boundary) for a DOM-like tree. This is a simplified .closest() used constantly in….

Learning goals

  • Translate the prompt into a clear javascript API signature and return shape.
  • Apply dom, tree, selectors techniques to implement dom tree walk 2: find closest ancestor.
  • Handle intermediate edge cases without sacrificing readability.
  • Reason about time/space complexity and trade-offs in javascript.

Key decisions to discuss

  • Define the exact input/output contract before coding.
  • Prioritize predictable edge-case handling over micro-optimizations.

Evaluation rubric

  • Correctness: covers required behaviors and edge cases.
  • Clarity: readable structure and predictable control flow.
  • Complexity: avoids unnecessary work for large inputs.
  • API discipline: no mutation of inputs; returns expected shape.
  • Testability: solution is easy to unit test.

Constraints / Requirements

  • Handle empty strings and mixed casing without errors.
  • Avoid prototype pitfalls when reading object keys.
  • Avoid deep recursion issues on large inputs.
  • Do not access the real DOM; use the provided node shape.
  • Handle empty or missing inputs without throwing errors.
  • Keep runtime close to linear time where possible.
  • Prefer a pure function: no side effects beyond the return value.

Mini snippet (usage only)

// Example usage
const node = /* dom tree walk 2: find closest ancestor input */;
const selector = /* config */;
const result = closestWithin(node, selector);
console.log(result);

// Edge case check
const empty = node && selector ?? null;
const fallback = closestWithin(node, selector);
console.log(fallback);

// Expected: describe output shape, not the implementation
// (no solution code in preview)

Common pitfalls

  • Mutating inputs instead of returning a new value.
  • Skipping edge cases like empty input, duplicates, or nulls.
  • Overlooking time complexity for large inputs.

Related questions

Upgrade to FrontendAtlas Premium to unlock this challenge. Already upgraded? Sign in to continue.