Element: setHTMLUnsafe() method

Baseline 2025
Newly available
*

Since September 2025, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.

Want more browser support for this feature? Tell us why.

* Some parts of this feature may have varying levels of support.

Warning: This method parses its input as HTML, writing the result into the DOM. APIs like this are known as injection sinks, and are potentially a vector for cross-site scripting (XSS) attacks, if the input originally came from an attacker.

You can mitigate this risk by always passing TrustedHTML objects instead of strings and enforcing trusted types. See Security considerations of the unsafe methods for more information.

Note: Element.setHTML() should almost always be used (where supported) instead of this method as it is always XSS-safe.

The setHTMLUnsafe() method of the Element interface is used to parse HTML input into a DocumentFragment and insert it into the DOM as a subtree of the element. The method may optionally sanitize the input while parsing it.

Syntax

js
setHTMLUnsafe(input)
setHTMLUnsafe(input, options)

Parameters

input

A TrustedHTML instance or string defining HTML to be parsed.

options Optional

An options object with the following optional parameters:

sanitizer Optional

A Sanitizer or SanitizerConfig object that defines which elements, attributes, comments, and processing instructions of the input will be allowed or removed. This can also be a string with the value "default", which applies a Sanitizer with the (XSS-safe) default sanitizer configuration. If not specified, no sanitizer is used.

Note that if you're using the same configuration multiple times, it's expected to be more efficient to use a Sanitizer and modify it when you need to.

runScripts Optional

A boolean value indicating whether any scripts included in the newly inserted HTML should run after inserting. The default is false.

Return value

None (undefined).

Exceptions

TypeError

This is thrown if:

  • input is passed a string when Trusted Types are enforced by a CSP and no default policy is defined.
  • options.sanitizer is passed a:
    • SanitizerConfig that isn't valid. For example, a configuration that includes both elements and removeElements configuration settings.
    • string that does not have the value "default".
    • value that is not a Sanitizer, SanitizerConfig, or string.
  • options.runScripts is true or options.sanitizer is specified when Trusted Types are enforced and no default policy defines createParserOptions — even if input is a TrustedHTML. (Passing a TrustedHTMLParserOptions as options avoids this.)

Description

The setHTMLUnsafe() method is used to parse HTML input into a DocumentFragment and insert it into the DOM as a subtree of the element. The method may optionally sanitize the input while parsing it.

For <template> elements, the HTML is inserted into the template contents (the template DocumentFragment), rather than as direct children.

The method uses context-aware HTML parsing, which may discard or rearrange elements depending on the parsing context (for example, a <col> element outside of a <table>).

Like all unsafe HTML setters, it will not remove additional items from its input, unless it is passed a sanitizer that removes them. However, it does not run scripts by default unless runScripts: true is provided as an option.

Unlike with Element.innerHTML, declarative shadow roots in the input will be parsed into the DOM. If the string of HTML defines more than one declarative shadow root in a particular shadow host then only the first ShadowRoot is created — subsequent declarations are parsed as <template> elements within that shadow root.

Security considerations

The suffix "Unsafe" in the method name indicates that it does not enforce removal of all XSS-unsafe HTML elements and attributes. This has extra security considerations as detailed in the sanitizer API "Security considerations of the unsafe methods" section and "When should the unsafe methods be used?" section.

Examples

setHTMLUnsafe() with Trusted Types

To mitigate the risk of XSS, we'll first create a TrustedHTML object from the string containing the HTML, and then pass that object to setHTMLUnsafe(). Since trusted types are not yet supported on all browsers, we define the trusted types tinyfill. This acts as a transparent replacement for the Trusted Types JavaScript API:

js
if (typeof trustedTypes === "undefined")
  trustedTypes = { createPolicy: (n, rules) => rules };

Next we create a TrustedTypePolicy that defines a createHTML() for transforming an input string into TrustedHTML instances. Commonly implementations of createHTML() use a library such as DOMPurify to sanitize the input as shown below:

js
const policy = trustedTypes.createPolicy("my-policy", {
  createHTML: (input) => DOMPurify.sanitize(input),
});

Then we use this policy object to create a TrustedHTML object from the potentially unsafe input string:

js
// The potentially malicious string
const untrustedString = "abc <script>alert(1)<" + "/script> def";
// Create a TrustedHTML instance using the policy
const trustedHTML = policy.createHTML(untrustedString);

Now that we have trustedHTML, the code below shows how you can use it with setHTMLUnsafe(). The input has been through the transformation function, so we don't pass a sanitizer to the method.

js
// Get the target Element with id "target"
const target = document.getElementById("target");

// setHTMLUnsafe() with no sanitizer
target.setHTMLUnsafe(trustedHTML);

Using setHTMLUnsafe() without Trusted Types

This example demonstrates the case where we aren't using trusted types, so we'll be passing sanitizer arguments.

The code creates an untrusted string and shows a number of ways a sanitizer can be passed to the method.

js
// The potentially malicious string
const untrustedString = "abc <script>alert(1)<" + "/script> def";

// Get the target Element with id "target"
const target = document.getElementById("target");

// Define custom Sanitizer and use in setHTMLUnsafe()
// This allows only elements: div, p, button, script
const sanitizer1 = new Sanitizer({
  elements: ["div", "p", "button", "script"],
});
target.setHTMLUnsafe(untrustedString, { sanitizer: sanitizer1 });

// Define custom SanitizerConfig within setHTMLUnsafe()
// Removes the <script> element but allows other potentially unsafe elements and attributes.
target.setHTMLUnsafe(untrustedString, {
  sanitizer: { removeElements: ["script"] },
});

setHTMLUnsafe() live example

This example provides a "live" demonstration of the method when called with different sanitizers. The code defines buttons that you can click to inject a string of HTML. One button injects the HTML without sanitizing it at all, and the second uses a custom sanitizer that allows <script> elements but not other unsafe items. The original string and injected HTML are logged so you can inspect the results in each case.

Note: Because we want to show how the sanitizer argument is used, the following code injects a string rather than a trusted type. You should not do this in production code.

HTML

The HTML defines two <button> elements for calling the method with different sanitizers, another button to reset the example, and a <div> element to inject the string into.

html
<button id="buttonNoSanitizer" type="button">None</button>
<button id="buttonAllowScript" type="button">allowScript</button>

<button id="reload" type="button">Reload</button>
<div id="target">Original content of target element</div>

JavaScript

First we define the string to sanitize, which will be the same for all cases. This contains the <script> element and the onclick handler, both of which are considered XSS-unsafe. We also define the handler for the reload button.

js
// Define unsafe string of HTML
const unsanitizedString = `
  <div>
    <p>Paragraph to inject into shadow DOM.
      <button onclick="alert('You clicked the button!')">Click me</button>
    </p>
    <script src="path/to/a/module.js" type="module"><\/script>
    <p data-id="123">Para with <code>data-</code> attribute</p>
  </div>
`;

const reload = document.querySelector("#reload");
reload.addEventListener("click", () => document.location.reload());

Next we define the click handler for the button that sets the HTML with no sanitizer. Generally we would expect the method to drop elements in the string that aren't allowed in the context (such as table-specific elements in a <div> element), but otherwise match the input string. In this case the strings should match.

js
const buttonNoSanitizer = document.querySelector("#buttonNoSanitizer");
buttonNoSanitizer.addEventListener("click", () => {
  // Set unsafe HTML without specifying a sanitizer
  target.setHTMLUnsafe(unsanitizedString);

  // Log HTML before sanitization and after being injected
  logElement.textContent =
    "No sanitizer: string should be injected without filtering\n\n";
  log(`\nunsanitized: ${unsanitizedString}`);
  log(`\n\nsanitized: ${target.innerHTML}`);
});

The next click handler sets the target HTML using a custom sanitizer that allows only <div>, <p>, and <script> elements. Note that because we're using the setHTMLUnsafe() method, <script> are not removed!

js
const allowScriptButton = document.querySelector("#buttonAllowScript");
allowScriptButton.addEventListener("click", () => {
  // Set the content of the element using a custom sanitizer
  const sanitizer1 = new Sanitizer({
    elements: ["div", "p", "script"],
  });
  target.setHTMLUnsafe(unsanitizedString, { sanitizer: sanitizer1 });

  // Log HTML before sanitization and after being injected
  logElement.textContent = "Sanitizer: {elements: ['div', 'p', 'script']}\n";
  log(`\nunsanitized: ${unsanitizedString}`);
  log(`\n\nsanitized: ${target.innerHTML}`);
});

Results

Click the "None" and "allowScript" buttons to see the effects of no sanitizer and a custom sanitizer, respectively.

When you click the "None" button, you should see that the input and output match, as no sanitizer is applied. When you click the "allowScript" button the <script> element is still present, but the <button> element is removed. With this approach you can create safe HTML, but you aren't forced to.

Using setHTMLUnsafe() with runScripts

This example demonstrates the case when we allow scripts to run using the runScripts option. This should be used with care.

js
// HTML from a trusted source
const htmlString = "<script src='example.js'></script><p>Other content</p>";

// Get the target Element with id "target"
const target = document.getElementById("target");

// No sanitizer is passed, so the <script> element is kept
// and also executes the script after insertion.
target.setHTMLUnsafe(htmlString, {
  runScripts: true,
});

Specifications

Specification
HTML
# dom-element-sethtmlunsafe

Browser compatibility

See also