HTML DOM Element insertAdjacentHTML() Method
- Previous Page insertAdjacentElement()
- Next Page insertAdjacentText()
- Go to the Previous Level HTML DOM Elements Object
Definition and Usage
insertAdjacentHTML()
The method inserts HTML code into the specified position.
Valid positions:
Value | Description |
---|---|
afterbegin | After the element begins (the first child element). |
afterend | After the element. |
beforebegin | Before the element. |
beforeend | Before the element ends (the last child element). |
Example
Example 1
Insert a new <p> element after the header element:
const h2 = document.getElementById("myH2"); let html = "<p>My new paragraph.</p>"; h2.insertAdjacentHTML("afterend", html);
Example 2
Using "afterbegin":
let html = "<span style='color:red'>My span</span>"; h2.insertAdjacentHTML("afterbegin", html);
Example 3
Using "beforebegin":
h2.insertAdjacentHTML("beforebegin", html);
Example 4
Using "beforeend":
h2.insertAdjacentHTML("beforeend", html);
Syntax
element.insertAdjacentHTML(position, html)
or
node.insertAdjacentHTML(position, html)
Parameter
Parameter | Description |
---|---|
position |
Required. The position relative to the element:
|
html | the HTML to be inserted. |
Browser support
All browsers support element.insertAdjacentHTML()
:
Chrome | IE | Edge | Firefox | Safari | Opera |
---|---|---|---|---|---|
Chrome | IE | Edge | Firefox | Safari | Opera |
Support | Support | Support | Support | Support | Support |
- Previous Page insertAdjacentElement()
- Next Page insertAdjacentText()
- Go to the Previous Level HTML DOM Elements Object