DOMParser and XMLSerializer

Two globals for moving between HTML strings and DOM: parse a fresh writable document, and serialise any node back to a string.

DOMParser

parseFromString

new DOMParser().parseFromString(html, type) → a writable document. This is the way to build markup to return from a read-only binding context: the parsed document (and everything reached from it) is writable even when the ambient document is not.

Divergence: the type argument is accepted but ignored — input is always parsed as text/html.

export default () => {
  const d = new DOMParser().parseFromString("<ul></ul>", "text/html");
  const li = d.createElement("li");
  li.textContent = "Item";
  d.querySelector("ul").appendChild(li);
  return d.querySelector("ul");   // return an element to splice in
};

XMLSerializer

serializeToString

new XMLSerializer().serializeToString(node) → a string. A document serialises whole; any other node serialises as its outer HTML (a fragment emits just its children).

const html = new XMLSerializer().serializeToString(element);

Serialising is rarely needed inside a binding — returning an element splices it into the page directly (see Returning DOM from a binding). Reach for serializeToString when you need the markup as a string — for example to hash it, store it in an attribute, or compare two subtrees.

See also