HTML DOM Element insertAdjacentHTML()

Example

Insert a new <p> element after a header element:

const h2 = document.getElementById("myH2");
let html = "<p>My new paragraph.</p>";
h2.insertAdjacentHTML("afterend", html);
Try it Yourself »

Description

The insertAdjacentHTML() method inserts HTML code into a specified position.

Legal positions:

ValueDescription
afterbeginAfter the beginning of the element (first child)
afterendAfter the element
beforebeginBefore the element
beforeendBefore the end of the element (last child)

Syntax

element.insertAdjacentHTML(position, html)
or
node.insertAdjacentHTML(position, html)

Parameters

Parameter Description
position Required.
A position relative to the element:
afterbegin
afterend
beforebegin
beforeend
html The HTML to insert.


More Examples

Example

Using "afterbegin":

let html = "<span style='color:red'>My span</span>"; h2.insertAdjacentHTML("afterbegin", html);
Try it Yourself »

Example

Using "beforebegin":

h2.insertAdjacentHTML("beforebegin", html);
Try it Yourself »

Example

Using "beforeend":

h2.insertAdjacentHTML("beforeend", html);
Try it Yourself »

Browser Support

element.insertAjacentHTML() is supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes Yes

Copyright 1999-2023 by Refsnes Data. All Rights Reserved.