DEV Community

Cover image for insertAdjacentHTML vs innerHTML
Jeannie Nguyen
Jeannie Nguyen

Posted on

16 2

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.

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

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.

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay