Steve Fenton

Avoid Expensive innerHTML Manipulation with insertAdjacentHTML

It is pretty well known these days that fiddling with innerHTML is terribly inefficient. It triggers serialization, and it can result in invalid markup. Nevertheless, you’ll still find this being done in many applications.

elem.innerHTML = elem.innerHTML + '<a href="">Visit Example Dot Com</a>';

// or

elem.innerHTML += '<a href="">Visit Example Dot Com</a>';

You can avoid many of the downsides to this approach using insertAdjacentHTML. Here’s a quick example that is equivalant to the previous operation, but without serialization or potential runiation.

elem.insertAdjacentHTML('beforeend', '<a href="">Visit Example Dot Com</a>');

That first parameter needs a little explanation. It just allows you to place your new HTML in one of four locations:

Immediately before the element
Immediately inside the element
Immediately before the closing tag of the element
Immediately after the closing tag of the element

So, if we take this HTML:

<div id="example">
    <div>Existing Element Content</div>

And we run all of the possible variations, as shown below:

const elem = document.getElementById('example');

elem.insertAdjacentHTML('beforebegin', '<div>Before Begin</div>');

elem.insertAdjacentHTML('afterbegin', '<div>After Begin</div>');

elem.insertAdjacentHTML('beforeend', '<div>Before End</div>');

elem.insertAdjacentHTML('afterend', '<div>After End</div>');

We end up with the following HTML:

<div>Before Begin</div>
<div id="example">
  <div>After Begin</div>
  <div>Existing Element Content</div>
  <div>Before End</div>
<div>After End</div>

Written by Steve Fenton on