AniUI Academy

Find a node by id in a DOM-like tree

mediumDOM & Utilities+250 XPPractice

Renderers, MDX pipelines and test utilities all keep a plain-object description of a document before it becomes real elements. Searching that structure is the same depth-first walk the browser does, and writing it makes the tree/traversal relationship concrete.

A node is a plain object { tag, attrs, children }. attrs is a plain object of attribute values and may be missing entirely. children is an array that may be missing, and it may hold either child nodes or plain strings for text content.

Implement findById(root, id). Search depth-first in pre-order — check a node before its children, and children left to right — and return a summary of the **first** node whose attrs.id equals id: { tag, depth, path }. depth is 0 for the root and one more for each level down. path is the array of child indices you followed from the root, so the root itself gives [].

String children are text, never match, and are skipped — but they still occupy their index, so the indices in path are positions in the raw children array. Return null when no node matches.

What it has to do

  • Search depth-first in pre-order and return the first match.
  • Return { tag, depth, path }, with depth 0 and path [] for the root.
  • Make path the child indices followed from the root, counting string children as positions.
  • Skip string children rather than throwing on them, and tolerate a missing attrs or children.
  • Return null when nothing matches.

Where it's been asked

  • Microsoft
  • Atlassian

From public interview reports — a problem very like this one has shown up in a round at these companies. Not an exhaustive list.

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...

Ready to check it?

5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.

Need a nudge?

Reveal a conceptual hint or the reference solution. Both were written and reviewed with the problem — no runtime magic.

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.