JAVASCRIPT

Efficiently Create and Insert HTML with `insertAdjacentHTML`

Learn to quickly insert HTML strings into the DOM without re-parsing the entire element, improving performance compared to reassigning `innerHTML` by specifying exact positions.

const targetElement = document.getElementById('targetDiv');

// Insert content before the target element itself
targetElement.insertAdjacentHTML('beforebegin', '<p>This content is before the target div.</p>');

// Insert content as the first child of the target element
targetElement.insertAdjacentHTML('afterbegin', '<h2>Title inside target div (first child)</h2>');

// Insert content as the last child of the target element
targetElement.insertAdjacentHTML('beforeend', '<p>This content is appended inside the target div.</p>');

// Insert content after the target element itself
targetElement.insertAdjacentHTML('afterend', '<div><hr><p>This content is after the target div.</p></div>');

// Example of dynamically added content for a list
const list = document.getElementById('myList');
const newItemHTML = '<li>New List Item ' + (list.children.length + 1) + '</li>';
list.insertAdjacentHTML('beforeend', newItemHTML);

/* HTML Structure Example:
<div id="targetDiv" style="border: 1px solid blue; padding: 10px;">
  Original content inside target div.
</div>

<ul id="myList">
  <li>Existing List Item 1</li>
</ul>
*/
How it works: `insertAdjacentHTML()` allows you to parse an HTML string and insert the resulting nodes directly into the DOM tree at a specified position relative to the element on which it is called. This method is often more performant than manipulating `innerHTML` directly for appending content, as `innerHTML` causes the browser to re-parse and recreate all children of an element every time it's assigned. `insertAdjacentHTML()` offers four positions: 'beforebegin' (before the element itself), 'afterbegin' (just inside the element, before its first child), 'beforeend' (just inside the element, after its last child), and 'afterend' (after the element itself).

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs