loading...
Cover image for insertAdjacentHTML vs innerHTML

insertAdjacentHTML vs innerHTML

jeannienguyen profile image Jeannie Nguyen ・2 min read

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.

Posted on by:

jeannienguyen profile

Jeannie Nguyen

@jeannienguyen

Writing about everything I learn on the web and sharing it so you can learn with me.

Discussion

pic
Editor guide
 

Was this found on MDN?

 

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