JavaScript Element getHTML() Method

Beginner
⏱️ 12 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Baseline 2024
Instance method

What You’ll Learn

Element.getHTML() is an instance method that serializes an element’s DOM to an HTML string. Learn basic serialization, how it compares to innerHTML, shadow DOM options (serializableShadowRoots and shadowRoots), and five try-it labs aligned with MDN.

01

Kind

Instance method

02

Returns

HTML string

03

Args

options (opt)

04

Shadow

Configurable

05

Default

Like innerHTML

06

Status

Baseline 2024

Introduction

When you need to export or copy the HTML inside an element, you might reach for innerHTML. getHTML() is the modern method that does the same job — and adds optional control over shadow DOM serialization.

Without any arguments, MDN states that getHTML() behaves like reading innerHTML: child nodes that are shadow roots are not serialized. Pass an options object when you need shadow content in the output string.

💡
Beginner tip

MDN notes that some browsers escape < and > in attribute values during serialization to reduce mutation XSS (mXSS) risk. Always treat serialized HTML as untrusted if it came from user input.

This page is part of JavaScript Element. Pair getHTML() with attachShadow() when building web components.

Understanding the getHTML() Method

Calling el.getHTML(options) walks the element’s descendants and returns their HTML serialization as a string.

  • It is an instance method on Element.
  • options (optional) — controls shadow root serialization (MDN).
  • serializableShadowRoots — include shadow roots marked serializable: true (default false).
  • shadowRoots — array of specific ShadowRoot objects to include (default []).
  • Returns a string of HTML markup.
  • No arguments → same result as el.innerHTML (MDN).
  • Throws no exceptions according to MDN.

📝 Syntax

General form of Element.getHTML (MDN):

JavaScript
getHTML(options)

Parameters

options (optional) — an object with:

  • serializableShadowRoots — boolean; include serializable shadow roots (default false, MDN).
  • shadowRoots — array of ShadowRoot objects to serialize regardless of mode (default [], MDN).

Return value

A string representing the HTML serialization of the element’s descendants (MDN).

Common patterns

JavaScript
// Basic — same as innerHTML
const html = card.getHTML();

// Include serializable shadow roots
const withShadow = host.getHTML({ serializableShadowRoots: true });

// Include specific shadow roots (open or closed)
const explicit = host.getHTML({ shadowRoots: [shadow] });

console.log(html);
console.log(withShadow.length);

⚡ Quick Reference

GoalCode
Basic serializeel.getHTML()
Same as innerHTMLel.getHTML() === el.innerHTML
Serializable shadowsel.getHTML({ serializableShadowRoots: true })
Explicit shadow rootsel.getHTML({ shadowRoots: [root] })
Return typestring
MDN statusBaseline 2024 (since September 2024)

🔍 At a Glance

Four facts to remember about Element.getHTML().

Returns
string

HTML markup

Baseline
2024

Since Sep 2024

Default
innerHTML

No shadow

Shadow
options

Configurable

📋 HTML serialization APIs

getHTML()innerHTMLouterHTML
TypeMethodProperty (get/set)Property (get/set)
ReturnsDescendant HTML stringDescendant HTML stringElement + descendants
Shadow DOMOptional via optionsNever serializedNever serialized
Can writeNo (read-only)YesYes (replaces element)
Best forExport with shadow controlSimple read/write markupClone/replace whole node

Examples Gallery

Examples follow MDN Element.getHTML() patterns. Use View Output or Try It Yourself for each case.

📚 Getting Started

Serialize plain HTML and compare with innerHTML.

Example 1 — Basic Serialization

Read the HTML markup inside a card element.

JavaScript
const card = document.getElementById("card");
const html = card.getHTML();

console.log(html);
// "<h2>Title</h2><p>Body text</p>"
Try It Yourself

How It Works

getHTML() returns a string of the element’s descendants only — not the outer tag of #card itself (same scope as innerHTML).

Example 2 — Same as innerHTML

Without options, MDN says getHTML() matches innerHTML.

JavaScript
const box = document.getElementById("box");

const byMethod = box.getHTML();
const byProperty = box.innerHTML;

console.log(byMethod === byProperty); // true (no shadow DOM)
Try It Yourself

How It Works

For elements without shadow roots, you can use either API. Choose getHTML() when you may need shadow options later.

📈 Shadow DOM Patterns

Include shadow content with serialization options.

Example 3 — serializableShadowRoots

Include shadow roots created with serializable: true (MDN).

JavaScript
const host = document.querySelector("info-box");

const plain = host.getHTML();
const withShadow = host.getHTML({ serializableShadowRoots: true });

console.log(plain.includes("Shadow message"));      // false
console.log(withShadow.includes("Shadow message")); // true
Try It Yourself

How It Works

Shadow roots are hidden by default. Set serializableShadowRoots: true only when the shadow was attached with serializable: true in attachShadow().

Example 4 — shadowRoots Array

Serialize specific shadow roots, including closed ones (MDN).

JavaScript
const host = document.getElementById("host");
const shadow = host.attachShadow({ mode: "closed" });
shadow.innerHTML = "Hidden shadow";

const html = host.getHTML({ shadowRoots: [shadow] });

console.log(html.includes("Hidden shadow"));
Try It Yourself

How It Works

The shadowRoots array lets you pass explicit ShadowRoot references. MDN: they are included regardless of open/closed mode or serializable flag.

Example 5 — Export a Template Snippet

Practical: copy serialized HTML for debugging or storage.

JavaScript
const template = document.getElementById("email-template");
const snippet = template.getHTML();

// Save or log the markup
localStorage.setItem("draft-html", snippet);
console.log(snippet.length);
Try It Yourself

How It Works

Use getHTML() as a read-only snapshot of current markup. Sanitize before re-injecting untrusted content anywhere in your app.

🚀 Common Use Cases

  • Exporting a component’s inner HTML for copy/paste or debugging.
  • Serializing web components that use shadow DOM (with options).
  • Saving draft markup to localStorage or sending to a server.
  • Building HTML diff tools that need a string snapshot.
  • Testing that rendered DOM matches expected markup.
  • Migrating from innerHTML reads to the modern serialization API.

🧠 How getHTML() Serializes Markup

1

Call on an element

element.getHTML() or pass an options object

Start
2

Walk descendants

Browser serializes child nodes; shadow roots follow option rules (MDN).

Serialize
3

Return HTML string

Markup of descendants only; browsers may escape attribute values for mXSS safety.

Result
4

Use or store safely

Log, copy, or save the string; sanitize before re-injecting untrusted HTML.

📝 Notes

  • Not Deprecated, Experimental, or Non-standard on MDN (Baseline 2024, September 2024).
  • Without options, behaves like innerHTML — shadow roots excluded (MDN).
  • serializableShadowRoots: true includes shadows marked serializable at attach time.
  • shadowRoots array can include open or closed roots you pass explicitly (MDN).
  • Some browsers escape </> in attribute values during serialization (MDN).
  • Related: innerHTML, attachShadow(), shadowRoot, JavaScript hub.

Browser Support

Element.getHTML() is Baseline 2024 (MDN: newly available across browsers since September 2024). Logos use the shared browser-image-sprite.png sprite from this project.

Baseline 2024

Element.getHTML()

Serialize element DOM to HTML with optional shadow root control — newer than innerHTML reads alone.

Baseline 2024 feature
Google Chrome Supported · recent versions
Yes
Microsoft Edge Supported · Chromium
Yes
Mozilla Firefox Supported · recent versions
Yes
Apple Safari Supported · recent versions
Yes
Opera Supported · Modern versions
Yes
Internet Explorer Not supported
No
getHTML() Growing

Bottom line: Feature-detect getHTML before use in production. Fallback to innerHTML for plain reads when shadow serialization is not needed.

Conclusion

Element.getHTML() serializes an element’s descendants to an HTML string. With no options it matches innerHTML; with shadow options it is the modern way to export markup from web components.

Continue with innerHTML, attachShadow(), shadowRoot, or the JavaScript hub.

💡 Best Practices

✅ Do

  • Feature-detect: typeof el.getHTML === "function"
  • Use for read-only serialization (not writing HTML)
  • Pass shadow options only when you need shadow content
  • Set serializable: true in attachShadow when exporting components
  • Sanitize serialized strings from untrusted sources

❌ Don’t

  • Assume shadow DOM is included by default
  • Re-inject serialized HTML without sanitization
  • Use instead of textContent for plain text
  • Expect IE or very old browsers to support it
  • Confuse with outerHTML (includes the element itself)

Key Takeaways

Knowledge Unlocked

Five things to remember about Element.getHTML()

Serialize DOM to HTML strings.

5
Core concepts
📄 02

Default

innerHTML

Same
✍️ 03

Shadow

options

Opt-in
04

Baseline

2024

Status
05

Safety

sanitize

mXSS

❓ Frequently Asked Questions

It serializes an element's DOM subtree to an HTML string. Without options, it behaves like reading Element.innerHTML — shadow roots are not included (MDN).
No. MDN marks Element.getHTML() as Baseline 2024 (newly available across browsers since September 2024). It is not Deprecated, Experimental, or Non-standard.
An optional object with serializableShadowRoots (boolean, default false) and shadowRoots (array of ShadowRoot objects, default []). These control whether and which shadow trees are serialized (MDN).
For plain elements without shadow DOM, getHTML() and innerHTML return the same markup. getHTML() adds options to include serializable or specified shadow roots — innerHTML never serializes shadow content.
When true, getHTML() includes child shadow roots that were created with serializable: true in attachShadow() (MDN).
No. MDN lists no exceptions for getHTML(). It always returns a string.
Did you know?

MDN: without arguments, getHTML() behaves the same as innerHTML. The main reason to use the method is optional shadow DOM serialization via serializableShadowRoots or shadowRoots.

More Element Topics

Browse Element methods and properties to keep building your DOM skills.

hasAttribute() →

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.

8 people found this page helpful