DOM - InsertAdjacent
Table of Contents
About
InsertAdjacent is a function that permits:
- to insert:
- a node (insertAdjacent)
- or html string (insertAdjacentHTML)
- into the DOM tree
- relatively to a node
Example
Insert an element (insertAdjacentElement)
let bodySibling = document.createElement('p');
bodySibling.innerText = 'Body Sibling Element';
document.body.insertAdjacentElement('afterend', bodySibling);
- Result:
Insert HTML directly (insertAdjacentHTML)
document.body.insertAdjacentHTML('afterend', '<p>Body Sibling HTML</p>');
- Result:
Syntax
element.insertAdjacentElement(position, siblingElement);
element.insertAdjacentHTML(position, text);
where position is:
- beforebegin
- afterbegin
- beforeend
- afterend
<!-- beforebegin -->
<element>
<!-- afterbegin -->
text
<!-- beforeend -->
</element>
<!-- afterend -->