JavaScript Element setHTML() Method

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

What You’ll Learn

Element.setHTML() is an instance method that sanitizes and injects HTML into an element using the HTML Sanitizer API. Learn MDN’s script-stripping demo, default vs custom Sanitizer options, why it beats innerHTML for user content, mutation XSS (mXSS) rules, and five try-it labs aligned with MDN.

01

Kind

Instance method

02

Returns

undefined

03

Args

input, options

04

Security

XSS-safe

05

Sanitizer

Default/custom

06

Status

Limited availability

Introduction

Setting HTML from a string is common in rich editors, comment widgets, and dynamic UIs. The classic approach — element.innerHTML = userHtml — is dangerous with untrusted input because it can run scripts or event handlers.

element.setHTML(input, options) parses the string, sanitizes it with the HTML Sanitizer API, and inserts the result as a subtree of the element (MDN). MDN recommends it as a drop-in replacement for innerHTML when the HTML comes from users.

💡
Always removed (MDN)

Even with a permissive custom sanitizer, setHTML() always strips XSS-unsafe elements (script, iframe, etc.) and event-handler attributes like onclick.

This page is part of JavaScript Element. Pair with getHTML() (serialize out) and insertAdjacentHTML() (insert at positions).

Understanding the setHTML() Method

Calling el.setHTML(input, options) sanitizes input and replaces the element’s contents with the safe subtree (MDN).

  • It is an instance method on Element.
  • input — HTML string to sanitize and inject (MDN).
  • options.sanitizer — optional Sanitizer, SanitizerConfig, or "default" (MDN).
  • Returns undefined.
  • Drops elements invalid in the current element’s context (e.g. tr outside table) (MDN).
  • Throws TypeError for invalid sanitizer config (MDN).
  • Unsafe alternative: setHTMLUnsafe() when you explicitly need unsanitized HTML (MDN).

📝 Syntax

General form of Element.setHTML (MDN):

JavaScript
setHTML(input)
setHTML(input, options)

Parameters

  • input — string of HTML to sanitize and inject (MDN).
  • options.sanitizer (optional) — Sanitizer, SanitizerConfig, or "default". Uses default config if omitted (MDN).

Return value

undefined (MDN).

Exceptions

  • TypeError — invalid SanitizerConfig, invalid string for sanitizer, or non-Sanitizer value (MDN).

Common patterns

JavaScript
const target = document.getElementById("target");
const userHtml = '<p>Hello</p><script>alert(1)</script>';

// Default sanitizer (MDN)
target.setHTML(userHtml);

// Custom Sanitizer
const sanitizer = new Sanitizer({ elements: ["div", "p", "button"] });
target.setHTML(userHtml, { sanitizer });

// SanitizerConfig inline
target.setHTML(userHtml, {
  sanitizer: { removeElements: ["div"] }
});

⚡ Quick Reference

GoalCode
Safe user HTMLel.setHTML(userString)
Custom sanitizerel.setHTML(html, { sanitizer })
Allow only div, pnew Sanitizer({ elements: ["div","p"] })
Remove specific tags{ sanitizer: { removeElements: ["div"] } }
Feature detecttypeof el.setHTML === "function"
MDN statusLimited availability (HTML spec)

🔍 At a Glance

Four facts to remember about Element.setHTML().

Returns
undefined

No value

Security
XSS-safe

Sanitized

Replaces
innerHTML

User HTML

Status
limited

Growing support

📋 setHTML() vs other HTML APIs

setHTML(input)innerHTML = htmlsetHTMLUnsafe()
SanitizesYes (always)NoNo
User inputRecommended (MDN)DangerousTrusted only
Custom rulesSanitizer optionsN/AN/A
ReturnsundefinedAssignment resultundefined
Best forUntrusted HTML stringsTrusted static markupExplicit unsafe needs

Examples Gallery

Examples follow MDN Element.setHTML() patterns. Use View Output or Try It Yourself for each case. Feature-detect setHTML and Sanitizer in supporting browsers.

📚 Getting Started

MDN’s basic demo—strip <script> from untrusted HTML.

Example 1 — Strip <script> (MDN)

Sanitize and inject HTML; unsafe tags are removed automatically.

JavaScript
const unsanitizedString = 'abc <script>alert(1)</script> def';
const target = document.getElementById("target");

target.setHTML(unsanitizedString);

console.log(target.innerHTML); // "abc  def" — script removed
Try It Yourself

How It Works

MDN: setHTML() parses the string, removes XSS-unsafe entities, and inserts the safe subtree. The script element never runs.

Example 2 — Default Sanitizer vs innerHTML

Use setHTML() instead of innerHTML for user-provided markup (MDN).

JavaScript
const userHtml = '<p>Safe text</p><img src=x onerror=alert(1)>';
const box = document.getElementById("box");

// Safe — onclick/onerror stripped (MDN)
box.setHTML(userHtml);

// Avoid with untrusted input:
// box.innerHTML = userHtml;

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

How It Works

MDN recommends setHTML() as a drop-in replacement for innerHTML when setting user-provided strings.

📈 Sanitizer Patterns

Custom Sanitizer configs and mXSS-safe workflows.

Example 3 — Custom Sanitizer (MDN)

Allow only specific elements; unsafe tags are still removed even if listed (MDN).

JavaScript
const unsanitizedString = '<div><p>Hi</p><script>alert(1)</script></div>';
const target = document.getElementById("target");

const sanitizer = new Sanitizer({
  elements: ["div", "p", "button", "script"] // script still removed (MDN)
});

target.setHTML(unsanitizedString, { sanitizer });

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

How It Works

MDN: even when script is in the allowed list, setHTML() removes XSS-unsafe elements and event-handler attributes.

Example 4 — SanitizerConfig with removeElements

Pass an inline config object to remove specific tags (MDN).

JavaScript
const html = '<div><p>Keep</p><button>Go</button></div>';
const target = document.getElementById("target");

target.setHTML(html, {
  sanitizer: { removeElements: ["div", "p", "button", "script"] }
});

console.log(target.innerHTML); // "" or minimal safe output
Try It Yourself

How It Works

MDN shows removeElements as an alternative to an allow-list. Unsafe entities are still stripped on top of your config.

Example 5 — Avoid Mutation XSS (mXSS)

Never re-parse serialized HTML with innerHTML (MDN).

JavaScript
const unsafeString = userInput;
const div = document.getElementById("a");
const otherDiv = document.getElementById("b");

// Safe
div.setHTML(unsafeString);

// UNSAFE — serialized HTML is no longer sanitized
// const serialized = div.innerHTML;
// otherDiv.innerHTML = serialized;

// Safe re-inject — setHTML re-sanitizes
const serialized = div.innerHTML;
otherDiv.setHTML(serialized);
Try It Yourself

How It Works

MDN: sanitization is context-aware. Only inject HTML strings through safe methods like setHTML(), not raw innerHTML assignment.

🚀 Common Use Cases

  • Rendering user-submitted rich text in comments or forums.
  • Injecting CMS or markdown-to-HTML output safely.
  • Building WYSIWYG editors that accept pasted HTML.
  • Replacing innerHTML assignments with sanitized insertion (MDN).
  • Applying custom Sanitizer allow-lists for constrained markup.
  • Pairing with getHTML() when round-tripping markup.

🧠 How setHTML() Sanitizes and Injects

1

Parse the input string

el.setHTML(input) receives an HTML string (MDN).

Input
2

Apply sanitizer rules

Default or custom Sanitizer config; drop invalid-in-context elements (MDN).

Sanitize
3

Strip XSS-unsafe entities

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

Security
4

Insert safe subtree

DOM updated; return value is undefined. Verify with innerHTML or DevTools.

📝 Notes

  • Limited availability on MDN — not yet Baseline in all major browsers. Feature-detect before use.
  • Not Deprecated, Experimental, or Non-standard — defined in the HTML specification.
  • Always removes XSS-unsafe elements/attributes, even with permissive sanitizers (MDN).
  • Do not re-parse serialized HTML with innerHTML (mutation XSS risk, MDN).
  • Use setHTMLUnsafe() only when you explicitly need unsafe HTML (MDN).
  • Related: getHTML(), innerHTML, insertAdjacentHTML(), JavaScript hub.

Limited Browser Support

Element.setHTML() has limited availability on MDN (HTML Sanitizer API). It is growing in Chromium-based browsers and Firefox. Logos use the shared browser-image-sprite.png sprite from this project.

Limited availability

Element.setHTML()

XSS-safe HTML injection with built-in sanitization — prefer over innerHTML for user content.

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

Bottom line: Feature-detect setHTML and Sanitizer before use. Provide innerHTML + DOMPurify or server-side sanitization as fallback where needed.

Conclusion

Element.setHTML() sanitizes and injects HTML strings safely. MDN recommends it over innerHTML for user-provided markup. Returns undefined and always strips XSS-unsafe content.

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

💡 Best Practices

✅ Do

  • Use setHTML() for untrusted user HTML (MDN)
  • Feature-detect: typeof el.setHTML === "function"
  • Reuse a Sanitizer instance for repeated configs (MDN)
  • Re-inject serialized HTML only via setHTML()
  • Provide a fallback sanitizer library where unsupported

❌ Don’t

  • Assign user strings to innerHTML
  • Re-parse innerHTML output into another element
  • Expect script to survive even if allow-listed
  • Use setHTMLUnsafe() for user content
  • Assume all browsers support the Sanitizer API yet

Key Takeaways

Knowledge Unlocked

Five things to remember about Element.setHTML()

Sanitize and inject — the safe way to set HTML from strings.

5
Core concepts
🛡️ 02

Security

XSS-safe

Sanitize
⚙️ 03

Sanitizer

default/custom

Config
⚠️ 04

mXSS

no innerHTML

Caution
🌐 05

Support

limited

Detect

❓ Frequently Asked Questions

It parses and sanitizes a string of HTML, then inserts it into the element as a DOM subtree. MDN recommends it as an XSS-safe replacement for innerHTML when setting user-provided HTML.
No. MDN marks it as Limited availability — not Baseline in all major browsers yet. It is not Deprecated, Experimental, or Non-standard; it is in the HTML specification.
undefined. There is no return value (MDN).
input (HTML string) and an optional options object with sanitizer — a Sanitizer, SanitizerConfig, or the string "default" (MDN).
innerHTML parses HTML without built-in sanitization. setHTML() always removes XSS-unsafe elements and attributes (script, onclick, etc.) even if a custom sanitizer would allow them (MDN).
MDN: only when you specifically need to allow unsafe elements and attributes. For untrusted user HTML, prefer setHTML().
Did you know?

MDN’s setHTML() demo shows that even when you allow script in a custom Sanitizer, the method still removes it — XSS-unsafe entities are always stripped on top of your configuration.

Next: setHTMLUnsafe()

Learn the injection-sink HTML API with optional sanitization and declarative shadow DOM.

setHTMLUnsafe() →

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