offline version v3


177 of 264 menu

insertAdjacentText method

The insertAdjacentText method allows you to insert a string anywhere on a page. The string is inserted relative to the target element. You can insert before the target element ('beforeBegin' insertion method), after it ('afterEnd' insertion method), and also at the beginning ('afterBegin insertion method ') or at the end (the 'beforeEnd' insertion method) of the target element.

Syntax

target element.insertAdjacentText(insertion method, text to insert);

Example . beforeBegin method

Let a target element be the #target element. We insert some text before it:

<div id="target"> <p>elem</p> </div> let target = document.querySelector('#target'); target.insertAdjacentText('beforeBegin', 'text');

The code execution result:

text <div id="target"> <p>elem</p> </div>

Example . afterEnd method

And now we insert a new paragraph after the target element:

<div id="target"> <p>elem</p> </div> let target = document.querySelector('#target'); target.insertAdjacentText('afterEnd', 'text');

The code execution result:

<div id="target"> <p>elem</p> </div> text

Example . afterBegin method

We insert a new paragraph at the beginning of the target element:

<div id="target"> <p>elem</p> </div> let target = document.querySelector('#target'); target.insertAdjacentText('afterBegin', 'text');

The code execution result:

<div id="target"> text <p>elem</p> </div>

Example . beforeEnd method

Let's insert a new paragraph at the end of the target element:

<div id="target"> <p>elem</p> </div> let target = document.querySelector('#target'); target.insertAdjacentText('beforeEnd', 'text');

The code execution result:

<div id="target"> <p>elem</p> text </div>

See also

  • the insertAdjacentElement method
    that inserts an element at a given location
  • the insertAdjacentHTML method
    that inserts a code at a given location
  • the prepend method
    that inserts elements at the start
  • the append method
    that inserts elements at the end
  • the appendChild method
    that inserts elements at the end of a parent
  • the insertBefore method
    that inserts elements before an element
enru