The insertAdjacentHTML() Method in JavaScript

The insertAdjacentHTML() method allows you to insert HTML code at a specific position relative to an existing element without overwriting its content.

element.insertAdjacentHTML(position, htmlString);

In the position string, you specify where to insert the HTML markup.

In htmlString, you pass the actual HTML code.

List of possible values:

ValueWhere it inserts
beforebeginBefore the element (outside)
afterbeginInside the element, at the beginning
beforeendInside the element, at the end
afterendAfter the element (outside)

Example of adding content before the element:

let box = document.getElementById('box');
box.insertAdjacentHTML('beforebegin', '<p>Text before the block</p>');

The insertAdjacentHTML() method allows you to inject code exactly where you need it without unnecessary changes or creating temporary elements.


Home About Links

Text me