Skip to curriculum
Jump to the editor

22.6. Serialize a DOM tree to HTML

Medium
Topics

This question is in

22. Serialization
20–35 min

Server rendering, "copy as HTML" in an editor, saving a drawing as SVG and snapshot tests all turn a DOM tree back into markup. The browser does it with outerHTML, following a short list of rules: which characters to escape where, which elements have no end tag, and which elements hold their text raw. Writing those rules yourself shows exactly why an HTML string can be safe or unsafe.

Write toHTML(node) in to-html.js. It returns the same string the browser's outerHTML gives for an element, and the same string a parent's innerHTML would give for a text node, a comment or a document fragment.

Signature

JAVASCRIPT
function toHTML(node) // returns a string
  • node: an element, a text node, a comment or a document fragment. Any other kind of node gives "".

Requirements

  1. An element is written as its start tag, its children in order, and its end tag: <p>hi <b>there</b></p>.
  2. Attributes are written in their order, as name="value" with double quotes, separated by single spaces. An attribute with an empty value is still written with ="".
  3. In attribute values, & becomes &amp;, " becomes &quot;, < becomes &lt;, > becomes &gt;, and a non-breaking space (U+00A0) becomes &nbsp;. A single quote is not escaped.
  4. In text, &, <, > and U+00A0 are escaped the same way; quotes are not.
  5. Void elements (area, base, basefont, bgsound, br, col, embed, frame, hr, img, input, keygen, link, meta, param, source, track, wbr) have no end tag, and their children (if a script added any) are not written.
  6. A comment is written as <!-- + its text + -->, unescaped.
  7. Text whose parent is a script, style, noscript, iframe, xmp, noembed, noframes or plaintext element is written raw. Text in every other element, textarea and title included, is escaped.
  8. HTML element names are written in lower case. Elements outside the HTML namespace (SVG) keep the case of their name, and of their attribute names.
  9. A template element writes the children of its content fragment.
  10. A document fragment is written as its children; a text node or comment can be passed on its own.
  11. Only attributes are written, never properties: typing into an input changes its value property, not its value attribute.
  12. The tree is not changed, and a tree of thousands of nodes works.

Examples

JAVASCRIPT
const link = document.createElement("a");
link.setAttribute("href", "/search?q=a&b");
link.setAttribute("title", 'say "hi"');
link.append("Tom & Jerry <3");
toHTML(link);
// '<a href="/search?q=a&amp;b" title="say &quot;hi&quot;">Tom &amp; Jerry &lt;3</a>'
JAVASCRIPT
const p = document.createElement("p");
p.append("line", document.createElement("br"), "next");
toHTML(p);   // '<p>line<br>next</p>'
JAVASCRIPT
const script = document.createElement("script");
script.textContent = "if (a < b) go();";
toHTML(script);   // '<script>if (a < b) go();</script>': not escaped

Environment

  • Plain JavaScript in a browser page; the tests build nodes and call the global toHTML from to-html.js, then compare with what the browser itself writes.
  • innerHTML, outerHTML, getHTML and XMLSerializer are not allowed: while your function runs, the tests replace them with functions that throw.
  • Doctypes, processing instructions, shadow roots and the namespace prefixes of XML documents are out of scope.

Hints

  1. Which property of a node tells you whether it is an element, a text node, a comment or a fragment?
  2. For a text node, where do you look to decide whether it is escaped?
  3. Where does a template keep its children?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…