目录

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:

Value Description
afterbegin After the beginning of the element (first child)
afterend After the element
beforebegin Before the element
beforeend Before the end of the element (last child)

Syntax

element.insertAdjacentHTML( position, html)
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