176 of 264 menu

insertAdjacentHTML method

The insertAdjacentHTML method allows you to insert a line of HTML code anywhere on a page. The code 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.insertAdjacentHTML(insertion method, code to insert);

Example . beforeBegin method

Let a target element be the #target element. Insert a new paragraph before it:

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

The code execution result:

<p>!</p> <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.insertAdjacentHTML('afterEnd', '<p>!</p>');

The code execution result:

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

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.insertAdjacentHTML('afterBegin', '<p>!</p>');

The code execution result:

<div id="target"> <p>!</p> <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.insertAdjacentHTML('beforeEnd', '<p>!</p>');

The code execution result:

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

See also

  • the insertAdjacentText method
    that inserts text at the given location
  • the insertAdjacentElement method
    that inserts an element 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
byenru