Skip to the solution
EasyFrontendAsked in 20244 min read

Custom getElementById traverse

1.6k views

The problem

Problem, as an interviewer would state it: "Implement your own version of document.getElementById(id), walking the DOM tree by hand rather than using the real built-in method. Show me it returns the exact same node the real one would."

Examples:

Code
findById(document.body, "submit-button") // the actual matching element, or null

Clarifying questions expected:

  • Should the search start from document/document.body, or should it accept any root node to search from?
  • What should it return if no element has that id — null, or undefined?
  • Should it stop at the FIRST match if (invalidly) multiple elements share an id, matching real browser behavior?

Code / implementation expected: Yes — real, direct proof against a real jsdom document that the hand-written traversal returns the identical node reference the browser's own getElementById would.

  • js-coding
  • utility
  • algorithm

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

4 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: a recursive getElementById-style tree walk returns the exact same real node as the browser's own native method

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 14 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextEasy

Immer-like draft proxies

Continue