Find a node by id in a DOM-like tree
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 }, withdepth0 andpath[]for the root. - Make
paththe child indices followed from the root, counting string children as positions. - Skip string children rather than throwing on them, and tolerate a missing
attrsorchildren. - Return
nullwhen nothing matches.
Your workspace
Ready to check it?
5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.
AI Crack & Solution Assist
Stuck? Get instant AI hints or break down the optimal solution.
Stuck? The javascript course covers everything this challenge needs.