Skip to content
AnswerWell geo Documentation

Research · 8 min read · Answerwell

HTML Fragment Parsing, Sanitization and Dynamic Insertion

How the HTML standard parses fragments, sanitizes markup on insert, and how safe setHTML differs from legacy innerHTML sinks.

This page summarises the WHATWG HTML Living Standard on dynamic markup insertion, HTML fragment parsing, DOM parsing and serialization, and the Sanitizer API, together with Chrome developer guidance on using those APIs safely when you turn strings into live DOM nodes.

Dynamic markup insertion: HTML parser vs XML parser

Section titled “Dynamic markup insertion: HTML parser vs XML parser”

APIs that insert markup into a document interact with a parser, so behaviour depends on whether the document is an HTML document (HTML parser) or an XML document (XML parser).

APIs for dynamically inserting markup into the document interact with the parser, and thus their behavior varies depending on whether they are used with HTML documents (and the HTML parser) or XML documents (and the XML parser).

— WHATWG HTML, Dynamic markup insertion

For XML documents, setters such as outerHTML throw SyntaxError when the string is not well-formed; for HTML, the HTML parser’s error-tolerant rules apply. Legacy APIs including innerHTML, outerHTML, insertAdjacentHTML(), and Range.createContextualFragment() perform no sanitization by default to remove dangerous elements and attributes such as script or event handler content attributes, as described in DOM parsing and serialization APIs.

HTML fragment parsing: what “context” means

Section titled “HTML fragment parsing: what “context” means”

When a string is parsed as an HTML fragment, the user agent runs the HTML fragment parsing algorithm. The fragment’s context element controls tokenizer state and insertion rules—for example, parsing inside title or textarea switches the tokenizer to RCDATA, while script uses the script data state.

Fragment parsing also respects parser flags such as parser scripting disabled (scripts may not run during parse), an optional parser sanitizer configuration (disallowed markup is not inserted into the DOM), and script target document when runScripts is enabled for fragment parsing initiated from APIs like createContextualFragment().

The HTML fragment parsing algorithm, given an Element or DocumentFragment target, a string input… return a DocumentFragment.

— WHATWG HTML, Parsing HTML fragments

If the input contains a script start tag without a matching end tag, that script’s already started is set when input ends, so it is never executed, even when runScripts is true. When sanitizing during parse, the fragment may be built in a temporary document and adopted into the target document afterward so removed elements never trigger fetches in the live document.

insertAdjacentHTML(): positions and template subtleties

Section titled “insertAdjacentHTML(): positions and template subtleties”

insertAdjacentHTML(position, string) parses the string and inserts nodes at beforebegin, afterbegin, beforeend, or afterend, as defined in The insertAdjacentHTML() method. Unlike some node APIs, it does not apply special handling for template elements; for template markup, the specification recommends templateEl.content.insertAdjacentHTML() instead of manipulating a template’s ordinary child list.

Safe vs unsafe insertion: which API removes script markup

Section titled “Safe vs unsafe insertion: which API removes script markup”

Modern HTML defines paired safe and unsafe insertion methods on Element, ShadowRoot, and related interfaces. The naming reflects XSS guarantees, not whether you should avoid the API entirely.

The “safe” methods will not generate any markup that executes script. That is, they are intended to be safe from XSS. The “unsafe” methods will parse and filter based on the provided configuration, but do not have the same safety guarantees by default.

— WHATWG HTML, Safe and unsafe

Action Safe (sanitizes by default) Unsafe (no default sanitizer; optional runScripts)
Set contents setHTML() / streamHTML() setHTMLUnsafe() / streamHTMLUnsafe()
Replace element replaceWithHTML() / streamReplaceWithHTML() replaceWithHTMLUnsafe() / …
Insert around element beforeHTML(), afterHTML(), etc. *Unsafe counterparts

Static methods take a complete HTML string; streaming methods return a WritableStream so chunks from fetch or other sources can be piped directly into the DOM, as outlined in Declarative partial updates and Out-of-Order (OOO) HTML Streaming.

Sanitizer API: parse and filter as the browser parses

Section titled “Sanitizer API: parse and filter as the browser parses”

The Sanitizer API lets a page parse untrusted HTML strings into a DOM tree while removing elements and attributes according to a SanitizerConfig. Chrome’s Sanitizing Untrusted HTML guide treats it as the primary client-side defence for user-generated HTML.

Web applications often need to process untrusted HTML strings, such as when rendering user-generated content or using client-side templates. Safely inserting these strings into the DOM requires careful sanitization to prevent DOM-based cross-site scripting (XSS) attacks.

— WHATWG HTML, Introduction to HTML sanitization

element.setHTML(html, options) parses, sanitizes, and inserts in one step. With the default sanitizer preset, unsafe elements (including those normatively marked Unsafe in the standard, frame, SVG script, and SVG use) are removed, and event handler content attributes are stripped by the remove-unsafe algorithm.

Custom rules use new Sanitizer(config) and { sanitizer: mySanitizer }. On safe methods you can only tighten the default allowlists—not configure a sanitizer that keeps script-capable markup through setHTML() or parseHTML(); if that were possible, the standard treats it as a bug.

By design, the setHTML(), streamHTML(), and parseHTML() methods remove script-capable markup regardless of the configuration supplied; if any configuration could preserve such markup through these methods, that would be a bug.

— WHATWG HTML, Security considerations

When you need a tree without attaching it yet, Document.parseHTML() returns a sanitized Document you can inspect; move nodes with replaceChildren(...doc.body.childNodes) rather than serializing and re-parsing, as warned in Sanitizing Untrusted HTML.

More permissive rules: setHTMLUnsafe() and runScripts

Section titled “More permissive rules: setHTMLUnsafe() and runScripts”

Use setHTMLUnsafe() with a custom Sanitizer only when safe methods cannot express your allowlist (for example, you must permit some otherwise-unsafe markup under strict control). The optional runScripts: true is for trusted HTML where scripts should run after insertion—for example piping a fetched partial with streamHTMLUnsafe({ runScripts: true }) as shown in Out-of-Order (OOO) HTML Streaming.

Serialization: getHTML(), innerHTML getters, and XML

Section titled “Serialization: getHTML(), innerHTML getters, and XML”

Serialization turns existing DOM nodes back into markup strings. element.getHTML({ serializableShadowRoots, shadowRoots }) uses the HTML fragment serialization algorithm and can include serializable or explicitly listed shadow roots (HTML serialization methods).

For XML documents, XMLSerializer.serializeToString() serialises to XML and throws InvalidStateError when the subtree cannot be represented as namespace-well-formed XML (The XMLSerializer interface). The XML fragment serialization algorithm lists DOM states that make a subtree unserialisable (invalid names, duplicate attributes, illegal comment syntax, and similar), as defined in Serializing XML fragments.

Coercing an HTML DOM into an XML pipeline may require dropping or renaming nodes that HTML allows but XML APIs reject, as described in Coercing an HTML DOM into an infoset.

Streaming untrusted text (including model output)

Section titled “Streaming untrusted text (including model output)”

When responses arrive in chunks, repeatedly assigning innerHTML reparses and replaces the entire subtree on every update—slow for rich formatting and dangerous if Markdown or HTML from an untrusted source is involved. Best practices to render streamed LLM responses recommends incremental DOM updates (for plain text, append() or insertAdjacentText('beforeend', chunk)) and, for Markdown, a streaming parser plus sanitization on the combined output so attacks split across chunks cannot slip through.

Built-in AI APIs: Do and don’t and the Language Model guidance align with the standard: treat model output as untrusted, prefer the Sanitizer API where supported, and avoid innerHTML on every chunk. Where the Sanitizer API is missing, feature-detect and fall back to a library such as DOMPurify, as described under fallbacks in Sanitizing Untrusted HTML.

Risk What the standard says
Server-side XSS Sanitizer runs in the DOM only; it does not address reflected or stored XSS on the server.
DOM clobbering Default config does not remove id / name; configure the sanitizer if needed.
Script gadgets Innocent-looking nodes may trigger framework code; review third-party libraries.
Mutation XSS (mXSS) Safe parse → innerHTML string → parse again can change structure; treat serialized HTML as untrusted.

For policy-level enforcement at sinks, Prevent DOM-based XSS attacks with Trusted Types complements setHTML(), which sanitizes without requiring a Trusted Types policy, while legacy sinks still accept TrustedHTML when enforcement is enabled (Web Security).

  • Assigning untrusted strings to innerHTML, outerHTML, or document.write() instead of textContent for plain text or setHTML() for HTML (Avoid dangerous DOM sinks).
  • Assuming a sanitizer checked once on a string still applies after getHTML() or innerHTML readback and a second parse (Mutation XSS).
  • Sanitizing each stream chunk in isolation instead of the accumulated markup (Render streamed Markdown).
  • Using insertAdjacentHTML on a template element’s children instead of template.content.insertAdjacentHTML() (insertAdjacentHTML()).
  • Calling createContextualFragment() expecting scripts not to run: by default its options set runScripts to true unless a Trusted Types default policy overrides parser options (createContextualFragment()).
  1. Search your codebase for dangerous sinks (innerHTML, outerHTML, document.write, eval, string setTimeout) and confirm untrusted data flows through setHTML(), textContent, or a reviewed Trusted Types policy (Web Security).
  2. In DevTools, exercise the insertion path with strings containing script, event handlers, and javascript: URLs; confirm safe methods strip them per Sanitizing Untrusted HTML.
  3. If you stream HTML or Markdown, profile with Paint flashing while updating chunks and verify you are not replacing the full subtree each tick (Best practices to render streamed LLM responses).
  4. When piping fetch streams, confirm you chose safe (streamHTML()) vs unsafe (streamHTMLUnsafe()) APIs and runScripts intentionally (Out-of-Order (OOO) HTML Streaming).
  5. You can check automatically in Answerwell (our tool): https://answerwell.org/workspace

If something on this page is wrong or unclear, email yimasynthetic@gmail.com with the page URL and the exact statement you are asking about, and we will correct or clarify it.