English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

HTML DOM insertAdjacentElement() method

HTML DOM Element Object

insertAdjacentElement()The method inserts a given element node into a specified position relative to the element that is called.

Syntax:

element.insertAdjacentElement(position, element)
var span = document.getElementsByTagName("span")[0];
var head = document.getElementsByTagName("h")[0];2")[0];
head.insertAdjacentElement("afterend", span);
Test and See‹/›

Browser compatibility

The numbers in the table specify the first browser version that fully supports the insertAdjacentElement() method:

Method
insertAdjacentElement()Is48IsIs8

Parameter value

ParameterDescription
positionThe position relative to the element.
Valid values:
  • "afterbegin"-After the start of the element (as the first child element)

  • "afterend"-After the element

  • "beforebegin"-Before the element

  • "Before end"-Before the end of the element (as the last child element)

elementThe element you want to insert

Technical details

Return value:The inserted element; if insertion fails, it returnsnull.
Exception cases:
  • SyntaxError-The specified position is not a recognizable value

  • TypeError-The specified element is not a valid element

More examples

Use the value "beginbegin":

var span = document.getElementsByTagName("span")[0];
var head = document.getElementsByTagName("h")[0];2")[0];
head.insertAdjacentElement("afterbegin", span);
Test and See‹/›

Using the "beforebegin" value:

var span = document.getElementsByTagName("span")[0];
var head = document.getElementsByTagName("h")[0];2")[0];
head.insertAdjacentElement("beforebegin", span);
Test and See‹/›

Using the "beforeend" value:

var span = document.getElementsByTagName("span")[0];
var head = document.getElementsByTagName("h")[0];2")[0];
head.insertAdjacentElement("beforeend", span);
Test and See‹/›

Related References

HTML DOM Reference:element.insertAdjacentHTML() method

HTML DOM Reference:element.insertAdjacentText() method

HTML DOM Reference:node.insertBefore() method

HTML DOM Reference:node.appendChild() method

HTML DOM Element Object