Element: setHTML() method

Limited availability

This feature is not Baseline because it does not work in some of the most widely-used browsers.

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

The setHTML() method of the Element interface is an XSS-safe method to parse and sanitize a string of HTML into a DocumentFragment using the HTML Sanitizer API and insert it into the DOM as a subtree of the element.

It is recommended (if supported) as a drop-in replacement for Element.innerHTML when setting a user-provided string of HTML.

Syntax

js
setHTML(input)
setHTML(input, options)

Parameters

input

A string defining HTML to be sanitized and injected into the element.

options Optional

An options object with the following optional parameters:

sanitizer

A Sanitizer or SanitizerConfig object which defines which items in the input will be removed, or the string "default" for the default sanitizer configuration.

If this option is omitted, the default sanitizer configuration is used. Note that if you're using the same configuration multiple times, it's likely to be more efficient to use a Sanitizer than a SanitizerConfig.

Return value

None (undefined).

Exceptions

TypeError

This is thrown if 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.

Description

setHTML() is an XSS-safe method to parse and sanitize a string of HTML into a DocumentFragment using the HTML Sanitizer API and insert it into the DOM as a subtree of the element.

It implements the same sanitization logic as all the other XSS-safe HTML setters.

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

setHTML() should be used instead of Element.innerHTML for inserting untrusted strings of HTML into an element. It should also be used instead of Element.setHTMLUnsafe(), unless there is a specific need to allow unsafe elements and attributes.

Examples

These examples show some of the ways you can use setHTML() to sanitize and inject a string of HTML.

Basic usage with default sanitizer

Using the default sanitizer:

js
const unsanitizedString = "<p><i>abc</i><script>alert(1)<" + "/script> def</p>";
const target = document.getElementById("target");

target.setHTML(unsanitizedString);
// Result is that the element is set to the sanitized string:
// <p><i>abc</i> def</p>

Using a custom sanitizer

Using a custom Sanitizer, that allows only the <div>, <p>, <button>, and <script> elements. Note that <script> is XSS-unsafe, so it will be removed anyway:

js
const unsanitizedString = "<p><i>abc</i><script>alert(1)<" + "/script> def</p>";
const target = document.getElementById("target");

const mySanitizer = new Sanitizer({
  elements: ["div", "p", "button", "script"],
});
target.setHTML(unsanitizedString, { sanitizer: mySanitizer });
// Result is that the element is set to the sanitized string:
// <p> def</p>

Using a custom sanitizer with removeElements

Using a custom SanitizerConfig, that removes only the <i> element, as well as other XSS-unsafe elements and attributes that are always removed by this method.

js
const unsanitizedString = "<p><i>abc</i><script>alert(1)<" + "/script> def</p>";
const target = document.getElementById("target");

target.setHTML(unsanitizedString, {
  sanitizer: { removeElements: ["i"] },
});
// Result is that the element is set to sanitized string:
// <p> def</p>

setHTML() 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 sanitize and inject a string of HTML using a default and a custom sanitizer, respectively. The original string and sanitized HTML are logged so you can inspect the results in each case.

HTML

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

html
<button id="buttonDefault" type="button">Default</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 the default sanitizer. This should strip out all unsafe entities before inserting the string of HTML. Note that you can see exactly which elements are removed in the Sanitizer() constructor examples.

js
const defaultSanitizerButton = document.querySelector("#buttonDefault");
defaultSanitizerButton.addEventListener("click", () => {
  // Set the content of the element using the default sanitizer
  target.setHTML(unsanitizedString);

  // Log HTML before sanitization and after being injected
  logElement.textContent =
    "Default sanitizer: remove script element, onclick attribute, data- attribute\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 setHTML method, <script> will also be 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.setHTML(unsanitizedString, { sanitizer: sanitizer1 });

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

Results

Click the "Default" and "allowScript" buttons to see the effects of the default and custom sanitizer, respectively.

Note that because we are using a safe sanitization method, in both cases the <script> element and onclick handler are removed, even if explicitly allowed by the sanitizer. However while the data- attribute is removed with the default sanitizer, it is allowed when we pass a sanitizer.

Specifications

Specification
HTML
# dom-element-sethtml

Browser compatibility

See also