22.6. Serialize a DOM tree to HTML
Topics
This question is in
22. SerializationServer 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
function toHTML(node) // returns a stringnode: an element, a text node, a comment or a document fragment. Any other kind of node gives"".
Requirements
- An element is written as its start tag, its children in order, and its end tag:
<p>hi <b>there</b></p>. - 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="". - In attribute values,
&becomes&,"becomes",<becomes<,>becomes>, and a non-breaking space (U+00A0) becomes . A single quote is not escaped. - In text,
&,<,>and U+00A0 are escaped the same way; quotes are not. - 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. - A comment is written as
<!--+ its text +-->, unescaped. - Text whose parent is a
script,style,noscript,iframe,xmp,noembed,noframesorplaintextelement is written raw. Text in every other element,textareaandtitleincluded, is escaped. - 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.
- A
templateelement writes the children of itscontentfragment. - A document fragment is written as its children; a text node or comment can be passed on its own.
- Only attributes are written, never properties: typing into an input changes its
valueproperty, not itsvalueattribute. - The tree is not changed, and a tree of thousands of nodes works.
Examples
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&b" title="say "hi"">Tom & Jerry <3</a>'const p = document.createElement("p");
p.append("line", document.createElement("br"), "next");
toHTML(p); // '<p>line<br>next</p>'const script = document.createElement("script");
script.textContent = "if (a < b) go();";
toHTML(script); // '<script>if (a < b) go();</script>': not escapedEnvironment
- Plain JavaScript in a browser page; the tests build nodes and call the global
toHTMLfromto-html.js, then compare with what the browser itself writes. innerHTML,outerHTML,getHTMLandXMLSerializerare 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
- Which property of a node tells you whether it is an element, a text node, a comment or a fragment?
- For a text node, where do you look to decide whether it is escaped?
- Where does a
templatekeep 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