Element: insertAdjacentText() method

TheinsertAdjacentText()method of theElementinterface, given a relative position and a string, inserts a new text node at the given position relative to the element it is called from.

Syntax

js
insertAdjacentText(where, data)

Parameters

where

A string representing the position relative to the element the method is called from; must be one of the following strings:

  • 'beforebegin':Before theelementitself.
  • 'afterbegin':Just inside theelement,before its first child.
  • 'beforeend':Just inside theelement,after its last child.
  • 'afterend':After theelementitself.
data

A string from which to create a new text node to insert at the given positionwhererelative to the element the method is called from.

Return value

None (undefined).

Exceptions

SyntaxErrorDOMException

Thrown ifwhereis not a recognized value.

Visualization of position names

html
<!-- beforebegin -->
<p>
<!-- afterbegin -->
foo
<!-- beforeend -->
</p>
<!-- afterend -->

Note:Thebeforebeginand afterendpositions work only if the node is in a tree and has an element parent.

Examples

js
beforeBtn.addEventListener( "click", () => {
para.insertAdjacentText( "afterbegin", textInput.value);
});

afterBtn.addEventListener( "click", () => {
para.insertAdjacentText( "beforeend", textInput.value);
});

Have a look at ourinsertAdjacentText.html demo on GitHub (see thesource codetoo.) Here we have a simple paragraph. You can enter some text into the form element, then press theInsert beforeandInsert afterbuttons to insert it before or after the existing paragraph text using insertAdjacentText().Note that the existing text node is not added to — further text nodes are created containing the new additions.

Specifications

Specification
DOM Standard
#dom-element-insertadjacenttext

Browser compatibility

BCD tables only load in the browser

See also