JavaScript Document parseHTML() Method

Beginner
⏱️ 12 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Limited availability
Static method

What You’ll Learn

Document.parseHTML() is a static method that parses and sanitizes an HTML string into a new Document that is XSS-safe (MDN). Learn default vs custom Sanitizer options, how it differs from parseHTMLUnsafe() and DOMParser, feature detection, and five examples with try-it labs.

01

Kind

Static method

02

Returns

Document

03

Args

input, options

04

Security

XSS-safe

05

MIME

text/html

06

Status

Limited availability

Introduction

Sometimes you need a whole Document from an HTML string—not just inject into one element. Older code often used DOMParser.parseFromString(html, "text/html"), which parses without the built-in XSS sanitizer that parseHTML() provides.

MDN: Document.parseHTML(input, options) parses and sanitizes the string and returns a new Document. The result has content type "text/html", character set UTF-8, and URL "about:blank".

💡
Prefer the safe API (MDN)

Use Document.parseHTML() instead of Document.parseHTMLUnsafe() unless you specifically need unsafe elements and attributes. XSS-unsafe entities are always removed by parseHTML(), even if a custom sanitizer would allow them.

Related tutorials: Element.setHTML(), Document constructor, contentType.

Understanding Document.parseHTML()

A static method on the Document interface—call it as Document.parseHTML(...), not on document instances (though engines may also expose it there).

  • input — HTML string to sanitize and parse (MDN).
  • options.sanitizer — optional Sanitizer, SanitizerConfig, or "default" (MDN).
  • Returns — a new Document (MDN).
  • Always sanitizes — removes XSS-unsafe elements/attributes (like after Sanitizer.removeUnsafe()) (MDN).
  • Declarative shadow roots — supported; only the first shadow root per host is created (MDN).
  • TypeError — invalid sanitizer config or value (MDN).

📝 Syntax

JavaScript
Document.parseHTML(input)
Document.parseHTML(input, options)

Parameters

  • input — string of HTML to sanitize and parse into a Document (MDN).
  • options (optional) — object with sanitizer: a Sanitizer, SanitizerConfig, or the string "default". If omitted, the default sanitizer is used (MDN).

Return value

A Document (MDN).

Exceptions

  • TypeError — invalid SanitizerConfig (e.g. both allowed and removed settings), a string other than "default", or a value that is not a Sanitizer / SanitizerConfig / string (MDN).

Common patterns

JavaScript
const html = '<p>Hello</p><script>alert(1)</script>';

// Default sanitizer (MDN)
const doc = Document.parseHTML(html);

// Custom Sanitizer (reuse for efficiency, MDN)
const sanitizer = new Sanitizer({ elements: ["div", "p", "span"] });
const doc2 = Document.parseHTML(html, { sanitizer });

// Explicit default
const doc3 = Document.parseHTML(html, { sanitizer: "default" });

⚡ Quick Reference

GoalCode / note
Parse safe DocumentDocument.parseHTML(html)
Custom sanitizerDocument.parseHTML(html, { sanitizer })
Read body HTMLdoc.body.innerHTML
Check MIMEdoc.contentType"text/html"
Feature-detecttypeof Document.parseHTML === "function"
MDN statusLimited availability (HTML spec)

🔍 At a Glance

Four facts about Document.parseHTML().

Call
Document.parseHTML

Static

Returns
Document

New tree

Security
XSS-safe

Sanitized

Status
limited

Not Baseline

📋 parseHTML() vs setHTML()

Document.parseHTML()element.setHTML()
KindStatic methodInstance method
OutputNew DocumentUpdates one element
ReturnsDocumentundefined
SanitizerYes (options)Yes (options)
Best forFull document from stringInject into existing node

Examples Gallery

Examples follow MDN Document: parseHTML(). Feature-detect Document.parseHTML in try-it labs—support is still limited.

📚 Getting Started

Parse an HTML string into a safe Document.

Example 1 — Parse and strip <script>

Default sanitizer removes XSS-unsafe tags (MDN).

JavaScript
const html = '<p>Hello</p><script>alert(1)</script>';
const doc = Document.parseHTML(html);

console.log(doc.body.innerHTML);
// "<p>Hello</p>" — script removed
Try It Yourself

How It Works

MDN: parseHTML() always removes XSS-unsafe entities before building the Document.

Example 2 — Document metadata (MDN)

The new Document has fixed content type, encoding, and URL.

JavaScript
const doc = Document.parseHTML("<h1>Title</h1>");

console.log({
  contentType: doc.contentType,   // "text/html"
  characterSet: doc.characterSet, // "UTF-8"
  URL: doc.URL                    // "about:blank"
});
Try It Yourself

How It Works

MDN documents these three properties for every Document created by parseHTML().

📈 Sanitizer, Detect & Import

Custom configs, feature detection, and moving nodes into the live page.

Example 3 — Custom Sanitizer

Allow only specific tags; unsafe tags are still stripped (MDN).

JavaScript
const html = '<div><p>Hi</p><script>alert(1)</script></div>';
const sanitizer = new Sanitizer({
  elements: ["div", "p", "script"] // script still removed (MDN)
});

const doc = Document.parseHTML(html, { sanitizer });
console.log(doc.body.innerHTML);
Try It Yourself

How It Works

MDN: reuse a Sanitizer instance when you apply the same config many times for efficiency.

Example 4 — Feature-detect safely

Limited availability—always check before calling.

JavaScript
function parseSafeHtml(html) {
  if (typeof Document.parseHTML === "function") {
    return Document.parseHTML(html);
  }
  // Fallback: wider support, but no built-in XSS strip — sanitize yourself
  return new DOMParser().parseFromString(html, "text/html");
}

const doc = parseSafeHtml("<p>OK</p>");
console.log(doc.body.textContent);
Try It Yourself

How It Works

In production, pair the DOMParser fallback with a sanitizer library (e.g. DOMPurify) when parseHTML is missing.

Example 5 — Import parsed nodes into the live page

Parse safely, then move nodes with importNode / append.

JavaScript
const userHtml = '<article><p>Comment</p><script>evil()</script></article>';
const parsed = Document.parseHTML(userHtml);
const host = document.getElementById("host");

// Import children into the current document
[...parsed.body.childNodes].forEach(function (node) {
  host.append(document.importNode(node, true));
});

console.log(host.innerHTML);
Try It Yourself

How It Works

For injecting into one element only, prefer setHTML(). Use parseHTML() when you need a full Document first.

🚀 Common Use Cases

  • Untrusted HTML strings — build a Document without running scripts (MDN).
  • Offline / preview documents — inspect body, title, or links before display.
  • CMS / markdown output — parse sanitized HTML batches into Documents.
  • Safer alternative to DOMParser — when Sanitizer API support is available.
  • Custom allow-lists — reuse a Sanitizer instance (MDN efficiency tip).
  • Not for element injection alone — use setHTML() when targeting one node.

🧠 How parseHTML() Builds a Safe Document

1

Pass an HTML string

Document.parseHTML(input) receives markup to sanitize (MDN).

Input
2

Apply sanitizer

Default or custom Sanitizer / SanitizerConfig (MDN).

Sanitize
3

Strip XSS-unsafe entities

script, event handlers, and other sinks removed even if allowed (MDN).

Security
4

Return a Document

text/html, UTF-8, about:blank (MDN). Read body or import nodes.

📝 Notes

  • MDN: Limited availability (not Baseline)—feature-detect before production use.
  • Not Deprecated, Experimental, or Non-standard — defined in the HTML specification.
  • Always removes XSS-unsafe elements/attributes, even with permissive sanitizers (MDN).
  • Prefer over parseHTMLUnsafe() unless you need unsafe HTML (MDN).
  • Trusted Types are not used to gate this method because it always sanitizes (MDN).
  • Related: setHTML(), contentType, characterSet, JavaScript hub.

Limited Browser Support

Document.parseHTML() has limited availability on MDN (HTML Sanitizer API / HTML spec). Support is emerging in Chromium and Firefox; Safari may lag. Logos use the shared browser-image-sprite.png sprite from this project.

Limited availability

Document.parseHTML()

XSS-safe static HTML → Document — feature-detect and provide a fallback.

Growing Limited availability
Google Chrome Emerging / recent versions · check
Partial
Microsoft Edge Follow Chromium support
Partial
Mozilla Firefox Emerging / recent versions · check
Partial
Apple Safari Limited or unavailable · check version
Partial
Opera Follow Chromium support
Partial
Internet Explorer Not supported
No
parseHTML() Partial

Bottom line: Feature-detect Document.parseHTML. Fallback to DOMParser plus a sanitizer library (e.g. DOMPurify) or server-side sanitization where support is missing.

Conclusion

Document.parseHTML() is the XSS-safe static way to turn an HTML string into a new Document. MDN prefers it over parseHTMLUnsafe() for untrusted markup. Support is still limited, so always feature-detect.

Continue with parseHTMLUnsafe(), setHTML(), contentType, ownerDocument, or the JavaScript hub.

💡 Best Practices

✅ Do

  • Call Document.parseHTML() for untrusted HTML strings (MDN)
  • Feature-detect with typeof Document.parseHTML === "function"
  • Reuse a Sanitizer instance for repeated configs (MDN)
  • Use setHTML() when injecting into one existing element
  • Provide a sanitizing fallback when support is missing

❌ Don’t

  • Use parseHTMLUnsafe() for user content (MDN)
  • Assume Baseline support in all browsers yet
  • Skip sanitization when falling back to DOMParser
  • Confuse static parseHTML with instance setHTML
  • Rely on Trusted Types to validate this call (MDN: not gated that way)

Key Takeaways

Knowledge Unlocked

Five things to remember about parseHTML()

Static, XSS-safe HTML → Document — feature-detect first.

5
Core concepts
🛡02

Security

XSS-safe

MDN
📄03

Returns

Document

text/html
04

Prefer

over Unsafe

MDN
🔍05

Status

limited

Detect

❓ Frequently Asked Questions

It is a static method that parses and sanitizes an HTML string and returns a new Document instance that is XSS-safe (MDN).
No. MDN marks Document.parseHTML() as Limited availability (not Baseline). It is not Deprecated, Experimental, or Non-standard; it is defined in the HTML specification.
MDN: content type "text/html", character set UTF-8, and URL "about:blank".
MDN: only when you specifically need to allow unsafe elements and attributes. Prefer Document.parseHTML() for untrusted HTML.
DOMParser.parseFromString() parses HTML or XML without the built-in XSS sanitizer that parseHTML() applies. parseHTML() always removes XSS-unsafe entities (MDN).
MDN: because this method always sanitizes XSS-unsafe entities, it is not secured or validated using the Trusted Types API.
Did you know?

MDN notes that if the HTML string defines more than one declarative shadow root on the same shadow host, only the first ShadowRoot is created—later declarations are parsed as elements inside that shadow root.

Next: parseHTMLUnsafe()

Learn the static injection-sink parser and when to prefer parseHTML() instead.

parseHTMLUnsafe() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful