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)

Demo:

let pSibling = document.createElement('p');
pSibling.innerText = 'A paragraph';
document.body.insertAdjacentElement('afterbegin', pSibling);
  • insertAdjacentElement is a advanced version of appendChild and therefore execute script node. Adding an hello world script.
let bodySibling = document.createElement('script');
bodySibling.text = 'console.log("Hello World !");';
document.body.insertAdjacentElement('beforeend', bodySibling);
  • Result:

Insert HTML directly (insertAdjacentHTML)

document.body.insertAdjacentHTML('afterend', '<p>Body Sibling HTML</p>');
  • Result:



insertAdjacentHTML is an advanced version of InnerHtml and therefore does not execute any script.

Syntax

element.insertAdjacentElement(position, siblingElement);
element.insertAdjacentHTML(position, text);

where position is:

  • beforebegin
  • afterbegin
  • beforeend
  • afterend
<!-- beforebegin -->
<element>
  <!-- afterbegin -->
  text
  <!-- beforeend -->
</element>
<!-- afterend -->

Security

insertAdjacentHTML is an advanced version of InnerHtml and therefore does not execute any script while insertAdjacentElement will execute them.


Powered by ComboStrap