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

HTML tag tree parser

602 views

The problem

Problem, as an interviewer would state it: "Write a minimal HTML parser converting a plain HTML string into a nested TAG TREE — no external libraries, just tracking open/close tags and building a simple tree of { tag, children } nodes."

Examples:

Code
parseHtml("<div><p>Hello</p></div>");
// { tag: "root", children: [{ tag: "div", children: [{ tag: "p", children: [...] }] }] }

Clarifying questions expected:

  • Does this need to handle real, malformed/unclosed HTML robustly, or is well-formed input a fair assumption?
  • Should self-closing tags (like a real <br/>) be handled without expecting a matching closing tag?
  • Should plain text content between tags become its own kind of node in the tree?

Code / implementation expected: Yes — real, direct proof against a real, nested HTML string with multiple tag levels and text content, producing the exact correct nested tree structure.

  • 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: parseHtml() produces the exact correct nested tree for a real HTML string with multiple tag levels, siblings, and text content

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 110 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 nextMedium

Polyfill Array.prototype.reduce

Continue