AniUI Academy
hard+350 XPPractice

Serialise a DOM-like tree to HTML

This is what a server renderer does at the end of its work, and what a static site generator does for every page. The rules are small but unforgiving: one missed escape is an injection bug, and one </br> is invalid markup.

A node is either a plain string, meaning text content, or a plain object { tag, attrs, children } where attrs and children may both be missing. Implement serialize(node) returning the HTML string, with no whitespace added anywhere.

Text nodes are escaped by replacing & with &amp;, < with &lt; and > with &gt; — quotes are left alone in text. Attribute values are escaped the same way plus " becoming &quot;.

Attributes are emitted in the attrs object's key order, each as a space then name="value". A value of true is a boolean attribute and is emitted as the bare name with no =; a value of false, null or undefined is omitted entirely; anything else is converted with String(value) and escaped.

The void elements area, base, br, col, embed, hr, img, input, link, meta, source, track, wbr are emitted as <tag ... /> — a single space before the slash — and their children are ignored. Every other tag is emitted as <tag ...> then its serialised children joined with nothing, then </tag>.

What it has to do

  • Serialise a string node as escaped text, escaping &, < and > only.
  • Escape attribute values for &, <, > and ", and emit attributes in key order.
  • Emit true as a bare boolean attribute and omit false, null and undefined values.
  • Emit void elements as <tag ... /> and ignore any children they have.
  • Add no whitespace of your own, and tolerate a missing attrs or children.

Your workspace

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.

AI Crack & Solution Assist

Stuck? Get instant AI hints or break down the optimal solution.

Stuck? The javascript course covers everything this challenge needs.