What is insertAdjacentElement in JavaScript?

The insertAdjacentElement method inserts an element at a given position, respective to the element at which insertAdjacentElement is called.

Syntax

targetElement.insertAdjacentElement(position, elementToBeInserted);

The position values can be:

  • beforebegin: The new element will be inserted before the targetElement.
  • afterbegin: The new element will be inserted before the first child of the targetElement.
  • beforeend: The new element will be inserted after the last child of the targetElement.
  • afterend: The new element will be inserted after the targetElement.

Let’s create a page with an unordered list as the parent and a list as the child, and then we’ll try to implement insertAdjacentElement using all four position values.


beforebegin

When we use beforebegin as the position of the new element, the new element will be inserted before the targetElement.

targetElement.insertAdjacentElement('beforebegin', elementToBeInserted);

afterbegin

When we use afterbegin as the position of the new element, the new element will be inserted before the first child of the targetElement.

targetElement.insertAdjacentElement('afterbegin', elementToBeInserted);

beforeend

When we use beforeend as the position of the new element, then the new element will be inserted after the last child of the targetElement.

targetElement.insertAdjacentElement('beforeend', elementToBeInserted);

afterend

When we use afterend as the position of the new element, the new element will be inserted after the targetElement.

targetElement.insertAdjacentElement('afterend', elementToBeInserted);

Free Resources