Element: insertAdjacentHTML() method
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since April 2018.
Warning: This method parses its input as HTML or XML, 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 reduce the risk by assigning TrustedHTML
objects instead of strings, and enforcing trusted types using the require-trusted-types-for
CSP directive.
This ensures that the input is passed through a transformation function, which has the chance to sanitize the input to remove potentially dangerous markup, such as <script>
elements and event handler attributes.
The insertAdjacentHTML()
method of the Element
interface parses the specified input as HTML or XML and inserts the resulting nodes into the DOM tree at a specified position.
Syntax
insertAdjacentHTML(position, input)
Parameters
position
-
A string representing the position relative to the element. Must be one of the following strings:
"beforebegin"
-
Before the element. Only valid if the element is in the DOM tree and has a parent element.
"afterbegin"
-
Just inside the element, before its first child.
"beforeend"
-
Just inside the element, after its last child.
"afterend"
-
After the element. Only valid if the element is in the DOM tree and has a parent element.
input
-
A
TrustedHTML
instance or string defining the HTML or XML to be parsed.
Return value
None (undefined
).
Exceptions
This method may raise a DOMException
of one of the following types:
NoModificationAllowedError
DOMException
-
Thrown if
position
is"beforebegin"
or"afterend"
and the element either does not have a parent or its parent is theDocument
object. SyntaxError
DOMException
-
Thrown if:
position
is not one of the four listed values.- The input is XML that is not well-formed.
TypeError
-
Thrown if the property is set to a string when Trusted Types are enforced by a CSP and no default policy is defined.
Description
The insertAdjacentHTML()
method does not reparse the element it is being used on, and thus it does not corrupt the existing elements inside that element. This avoids the extra step of serialization, making it much faster than direct innerHTML
manipulation.
Where <p>
is the element, we can visualize the possible positions for the inserted content "foo" as follows:
<!-- beforebegin -->
<p>
<!-- afterbegin -->
foo
<!-- beforeend -->
</p>
<!-- afterend -->
The method does not include any special handling for <template>
elements.
In most cases developers should use insertAdjacentHTML()
on the template's content
property instead of directly manipulating the child nodes of a template element.
Security considerations
The method does not perform any sanitization to remove XSS-unsafe elements such as <script>
, or event handler content attributes.
When inserting HTML into a page using insertAdjacentHTML()
, you should pass TrustedHTML
objects instead of strings, and enforce trusted types using the require-trusted-types-for
CSP directive.
This ensures that the input is passed through a transformation function, which has the chance to sanitize the input to remove potentially dangerous markup before it is injected.
The Element.insertAdjacentText()
method or Node.textContent
should be used when you know that the user provided content should be plain text.
This inserts the input as raw text instead of parsing it as HTML.
Examples
Inserting HTML
This example demonstrates the four insertion positions. All inserted text is bold, while text inserted inside the element is further styled as red monotype (code).
HTML
<select id="position">
<option>beforebegin</option>
<option>afterbegin</option>
<option>beforeend</option>
<option>afterend</option>
</select>
<button id="insert">Insert HTML</button>
<button id="reset">Reset</button>
<p>
Some text, with a <code id="subject">code-formatted element</code> inside it.
</p>
CSS
code {
color: red;
}
JavaScript
While not required for this example, below we follow the recommendation of defining a policy to create TrustedHTML
objects from the input (we should also enforce the policy safe-content-policy
using CSP).
In this case we know the input is safe so this policy passes it through without modification.
The commented code shows how you might instead use the "DOMPurify" library to sanitize content that wasn't trusted.
const policy = trustedTypes.createPolicy("safe-content-policy", {
createHTML: (input) => {
// DOMPurify.sanitize(input);
return input;
},
});
const unsafeText = "<strong>inserted text</strong>";
const trustedHTML = policy.createHTML(unsafeText);
The remaining code inserts the trusted HTML at the selected position relative to the element with id subject
.
const insert = document.querySelector("#insert");
insert.addEventListener("click", () => {
const subject = document.querySelector("#subject");
const positionSelect = document.querySelector("#position");
subject.insertAdjacentHTML(positionSelect.value, trustedHTML);
});
const reset = document.querySelector("#reset");
reset.addEventListener("click", () => {
document.location.reload();
});
Result
Specifications
Specification |
---|
HTML # the-insertadjacenthtml()-method |
See also
Element.insertAdjacentElement()
Element.insertAdjacentText()
XMLSerializer
: Serialize a DOM tree into an XML string- Trusted Types API
- hacks.mozilla.org guest post by Henri Sivonen including benchmark showing that
insertAdjacentHTML()
can be way faster in some cases.