Element: setHTML() method

Secure context: This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

The setHTML() method of the Element interface is used to parse and sanitize a string of HTML and then insert it into the DOM as a subtree of the element. It should be used instead of Element.innerHTML for inserting untrusted strings of HTML into an element.

The parsing process drops any elements in the HTML string that are invalid in the context of the current element, while sanitizing removes any unsafe or otherwise unwanted elements, attributes or comments. The default Sanitizer() configuration strips out XSS-relevant input by default, including <script> tags, custom elements, and comments. The sanitizer configuration may be customized using Sanitizer() constructor options.


setHTML(input, options)



A string defining HTML to be sanitized.

options Optional

An options object with the following optional parameters:


A Sanitizer object which defines what elements of the input will be sanitized. If not specified, the default Sanitizer object is used.

Return value

None (undefined).




The code below demonstrates how to sanitize a string of HTML and insert it into the Element with an id of target.

const unsanitized_string = "abc <script>alert(1)<" + "/script> def"; // Unsanitized string of HTML
const sanitizer1 = new Sanitizer(); // Default sanitizer;

// Get the Element with id "target" and set it with the sanitized string.
  .setHTML(unsanitized_string, { sanitizer: sanitizer1 });

// Result (as a string): "abc  def"

Note: This example uses the default sanitizer. The Sanitizer constructor is used to configure sanitizer options.


HTML Sanitizer API
# dom-element-sethtml

Browser compatibility

BCD tables only load in the browser