Skip to the solution
HardLow-Level DesignAsked in 20247 min read

Virtual DOM element mapper

992 views

The problem

Problem, as an interviewer would state it: "Implement createElement(vnode) — converting a simple {tag, props, children} vnode tree into an actual, real DOM element, including correctly wiring up event handlers."

Examples:

Code
createElement(h("div", { class: "box" }, h("span", {}, "Hello")));
// a real, live <div class="box"><span>Hello</span></div> DOM element

Clarifying questions expected:

  • How should a prop name like onClick be distinguished from a genuine HTML attribute like class, and wired up correctly?
  • Should a string child be handled differently from an object (element) child?
  • Does this need to support recursively building an arbitrarily deep tree of nested children?

Code / implementation expected: Yes — real, direct proof against a real jsdom document: the exact rendered outerHTML, correct nested children and text content, and a real, dispatched click event correctly firing a vnode's own attached handler.

  • 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

7 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: createElement() produces the exact correct real outerHTML against a jsdom document, and a real dispatched click event fires the vnode's own handler

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 142 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 nextHard

Implement deepClone — handle Dates, RegExp, Map, Set & circular refs

Continue