Element: insertAdjacentHTML() method

The insertAdjacentHTML() method of the Element interface parses the specified text as HTML or XML and inserts the resulting nodes into the DOM tree at a specified position.


insertAdjacentHTML(position, text)



A string representing the position relative to the element. Must be one of the following strings:


Before the element. Only valid if the element is in the DOM tree and has a parent element.


Just inside the element, before its first child.


Just inside the element, after its last child.


After the element. Only valid if the element is in the DOM tree and has a parent element.


The string to be parsed as HTML or XML and inserted into the tree.

Return value

None (undefined).


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 the Document object.

SyntaxError DOMException

Thrown if position is not one of the four listed values.


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.

We can visualize the possible positions for the inserted content as follows:

<!-- beforebegin -->
  <!-- afterbegin -->
  <!-- beforeend -->
<!-- afterend -->

Security considerations

When inserting HTML into a page by using insertAdjacentHTML(), be careful not to use user input that hasn't been escaped.

You should not use insertAdjacentHTML() when inserting plain text. Instead, use the Node.textContent property or the Element.insertAdjacentText() method. This doesn't interpret the passed content as HTML, but instead inserts it as raw text.


Inserting HTML


<select id="position">

<button id="insert">Insert HTML</button>
<button id="reset">Reset</button>

  Some text, with a <code id="subject">code-formatted element</code> inside it.


code {
  color: red;


const insert = document.querySelector("#insert");
insert.addEventListener("click", () => {
  const subject = document.querySelector("#subject");
  const positionSelect = document.querySelector("#position");
    "<strong>inserted text</strong>"

const reset = document.querySelector("#reset");
reset.addEventListener("click", () => {



DOM Parsing and Serialization
# dom-element-insertadjacenthtml

Browser compatibility

BCD tables only load in the browser

See also