How to use insertAdjacentHTML

By

Learn how to use the DOM insertAdjacentHTML method to insert HTML into a page, and the four positions beforebegin, afterbegin, beforeend and afterend.

~~~

insertAdjacentHTML is a DOM method we can call on any element to add new content to a page. You give it a position and a string of HTML, and the browser parses the string and inserts the resulting nodes for you.

The method is called on an element and accepts 2 parameters: the position, and a string containing HTML.

Here’s an example:

const notice = `<div>
    Your order shipped!
  </div>
`

document.querySelector('#messages').insertAdjacentHTML('afterend', notice)

Notice the afterend string.

This represents the position where we’re going to add the HTML, relative to the element.

We have 4 possible positions:

Say we have this list:

<ul id="groceries">
  <li>Milk</li>
  <li>Bread</li>
</ul>

Here’s how we would add a new item at the end of it:

document.querySelector('#groceries')
  .insertAdjacentHTML('beforeend', '<li>Eggs</li>')

beforeend puts the new li after the last existing child, so it lands inside the list, at the bottom. With afterbegin it would go to the top instead. beforebegin and afterend would place it outside the ul entirely, as a sibling.

Why not just use innerHTML?

You could append content by doing element.innerHTML += '<li>Eggs</li>'. But that has a hidden cost.

innerHTML += reads the whole content of the element as a string, adds your new piece, and re-parses everything from scratch. All the existing DOM nodes inside are destroyed and rebuilt. Any event listeners attached to them are gone, and form fields lose their state.

insertAdjacentHTML only parses the new string. The existing nodes are untouched, listeners keep working. That’s why I reach for it whenever I add content next to existing elements.

Be careful with untrusted content

The string you pass is parsed as real HTML. If it contains user input, a malicious value can inject markup into your page and open the door to XSS attacks.

The fix: when you’re inserting plain text that comes from users, use the sibling method insertAdjacentText() instead. Same positions, but the string is inserted as text, never interpreted as HTML.

~~~

Related posts about platform: