DEV Community

Cover image for insertAdjacentHTML vs innerHTML
Jeannie Nguyen
Jeannie Nguyen

Posted on

insertAdjacentHTML vs innerHTML

I was building a module the other day that could be imported and used from anywhere on the site. While building the module, I ran into the issue of needing to add HTML without altering the existing HTML and corrupting the DOM. That's when I found out about insertAdjacentHTML.

Here's a quick breakdown on how insertAdjacentHTML and innerHTML works.

innerHTML

Using innerHTML is the quickest way to modify HTML. You can use it to replace the contents of an element.

Here's the syntax:
Alt Text

Let's break down element.innerHTML += "content";
The browser does the following:

  1. Gets the value of innerHTML by serializing element's descendents.
  2. Appends "content" to the string.
  3. Removes the children of element.
  4. Parses the new string that contains the serialization of the old descendants, along with the new markup.

Using innerHTML means that any JavaScript references to the descendants of element will be removed.

When you use insertAdjacentHTML, adding additional content will not corrupt the existing JS references and the existing nodes are not altered.

insertAdjacentHTML

insertAdjacentHTML is a method that takes two string arguments. The first being the insertion point relative to the node that insertAdjacentHTML is invoked on: beforebegin, afterbegin, beforeend, or afterend. The second argument is a string containing the HTML markup you want to add.

Here is a visualization of the position names:
Alt Text

The insertAdjacentHTML method does not reparse the element it is invoked on, so it does not corrupt the element. Since insertAdjacentHTML does not continuously serialize and reparse elements, it is much faster than innerHTML, where appending gets slower each time there is more content.

Top comments (2)

Collapse
 
tranpeter08 profile image
Peter Tran

Was this found on MDN?

Collapse
 
jeannienguyen profile image
Jeannie Nguyen

Hey, Peter! Yeah, the screenshots are pulled from MDN.