Element: outerHTML property
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
Warning:This property parses its input as HTML, writing the result into the DOM.APIs like this are known asinjection sinks, and are potentially a vector forcross-site scripting (XSS) attacks, if the input originally came from an attacker.
You can mitigate this risk by always assigningTrustedHTML objects instead of strings andenforcing trusted types.SeeSecurity considerations for more information.
TheouterHTML attribute of theElement interface gets or sets the HTML or XML markup of the element and its descendants, omitting anyshadow roots in both cases.
To get or set the contents of an element, use theinnerHTML property instead.
In this article
Value
Getting the property returns a string containing an HTML serialization of theelement and its descendants.
Setting the property accepts either aTrustedHTML object or a string.The input is parsed as HTML and replaces the element and all its descendants with the result.When set to thenull value, thatnull value is converted to the empty string (""), soelement.outerHTML = null is equivalent toelement.outerHTML = "".
Exceptions
NoModificationAllowedErrorDOMExceptionThrown if an attempt was made to set
outerHTMLon an element which is a direct child of aDocument, such asDocument.documentElement.SyntaxErrorDOMExceptionThrown if an attempt was made to set
outerHTMLusing an XML input which is not well-formed.TypeErrorThrown if the property is set to a string whenTrusted Types areenforced by a CSP and no default policy is defined.
Description
outerHTML gets a serialization of the element, or sets HTML or XML that should be parsed to replace it within the element's parent.
If the element has no parent node, setting itsouterHTML property will not change it or its descendants.For example:
const div = document.createElement("div");div.outerHTML = '<div>test</div>';console.log(div.outerHTML); // output: "<div></div>"Also, while the element will be replaced in the document, the variable whoseouterHTML property was set will still hold a reference to the original element:
const p = document.querySelector("p");console.log(p.nodeName); // shows: "P"p.outerHTML = "<div>This div replaced a paragraph.</div>";console.log(p.nodeName); // still "P";Escaped attribute values
The returned value will escape some values in HTML attributes.Here we see that the& character is escaped:
const anchor = document.createElement("a");anchor.href = "https://developer.mozilla.org?a=b&c=d";console.log(anchor.outerHTML); // output: "<a href='https://developer.mozilla.org?a=b&c=d'></a>"Some browsers also serialize the< and> characters as< and> when they appear in attribute values (seeBrowser compatibility).This is to prevent a potential security vulnerability (mutation XSS) in which an attacker can craft input that bypasses asanitization function, enabling a cross-site scripting (XSS) attack.
Shadow DOM considerations
The serialization of the DOM tree read from the property does not includeshadow roots.If you want to get an HTML serialization of an element that includes shadow roots, you must instead use theElement.getHTML() method.Note that this gets thecontents of the element.
Similarly, when setting element content usingouterHTML, the HTML input is parsed into DOM elements that do not contain shadow roots.So for example<template> is parsed into asHTMLTemplateElement, whether or not theshadowrootmode attribute is specified.If you want to set an element'scontents from an HTML input that includes declarative shadow roots, you must instead useElement.setHTMLUnsafe() orShadowRoot.setHTMLUnsafe().
Security considerations
TheouterHTML property is possible vector forcross-site scripting (XSS) attacks, as it can be used to inject potentially unsafe strings provided by a user into the DOM.While the property does prevent<script> elements from executing when they are injected, it is susceptible to many other ways that attackers can craft HTML to run malicious JavaScript.For example, the following example would execute the code in theerror event handler, because the<img>src value is not a valid image URL:
const name = "<img src='x' onerror='alert(1)'>";element.outerHTML = name; // shows the alertYou can mitigate these issues by always assigningTrustedHTML objects instead of strings, andenforcing trusted types using therequire-trusted-types-for CSP directive.This ensures that the input is passed through a transformation function, which has the chance tosanitize the input to remove potentially dangerous markup before it is injected.
Examples
>Getting the serialization of an element
ReadingouterHTML causes the user agent to serialize the element.
Given the following HTML:
<div> <p>Content</p> <p>Further Elaborated</p></div>You can get and log the markup for the<div> as shown:
const myElement = document.querySelector("#example");const contents = myElement.outerHTML;console.log(contents);// '<div>\n <p>Content</p>\n <p>Further Elaborated</p>\n</div>'Replacing the element
In this example we'll replace an element in the DOM by assigning HTML to the element'souterHTML property.To mitigate the risk of XSS, we'll first create aTrustedHTML object from the string containing the HTML, and then assign that object toouterHTML.
Trusted types are not yet supported on all browsers, so first we define thetrusted types tinyfill.This acts as a transparent replacement for the Trusted Types JavaScript API:
if (typeof trustedTypes === "undefined") trustedTypes = { createPolicy: (n, rules) => rules };Next we create aTrustedTypePolicy that defines acreateHTML() for transforming an input string intoTrustedHTML instances.Commonly implementations ofcreateHTML() use a library such asDOMPurify to sanitize the input as shown below:
const policy = trustedTypes.createPolicy("my-policy", { createHTML: (input) => DOMPurify.sanitize(input),});Then we use thispolicy object to create aTrustedHTML object from the potentially unsafe input string, and assign the result to the element:
// The potentially malicious stringconst untrustedString = "<p>I might be XSS</p><img src='x' onerror='alert(1)'>";// Create a TrustedHTML instance using the policyconst trustedHTML = policy.createHTML(untrustedString);// Inject the TrustedHTML (which contains a trusted string)const element = document.querySelector("#container");element.outerHTML = trustedHTML; // Replaces the element with id "container"// Note that the #container div is no longer part of the document tree,Warning:While you can directly assign a string toouterHTML this is asecurity risk if the string to be inserted might contain potentially malicious content.You should useTrustedHTML to ensure that the content is sanitized before it is inserted, and you should set a CSP header toenforce trusted types.
Specifications
| Specification |
|---|
| HTML> # dom-element-outerhtml> |
Browser compatibility
See also
- Serializing DOM trees into XML strings:
XMLSerializer - Parsing XML or HTML into DOM trees:
DOMParser HTMLElement.outerText