DOM - InsertAdjacent

About

InsertAdjacent is a function that permits:

  • to insert:
    • a node (insertAdjacent)
    • or html string (insertAdjacentHTML)
  • into the DOM tree
  • relatively to a node
  • at this positions (as a child or sibling)

_

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 -->

Powered by ComboStrap