W3cubDocs

/Web APIs

Element: setHTML() method

Experimental: This is an experimental technology
Check the Browser compatibility table carefully before using this in production.

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.

Note: Use Sanitizer.sanitizeFor() instead of this method if the string must be inserted into the DOM at a later point, for example if the target element is not yet available.

Syntax

js

setHTML(input, options)

Parameters

input

A string defining HTML to be sanitized.

options Optional

An options object with the following optional parameters:

sanitizer

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).

Exceptions

None.

Examples

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

js

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.
document
  .getElementById("target")
  .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.

Specifications

Browser compatibility

Desktop Mobile
Chrome Edge Firefox Internet Explorer Opera Safari WebView Android Chrome Android Firefox for Android Opera Android Safari on IOS Samsung Internet
setHTML 105–119 105–119 94 No 91 No 105 105–119 No 72 No 20.0

See also

© 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/Element/setHTML