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.
Using innerHTML is the quickest way to modify HTML. You can use it to replace the contents of an element.
Let's break down
element.innerHTML += "content";
The browser does the following:
- Gets the value of
"content"to the string.
- Removes the children of
- Parses the new string that contains the serialization of the old descendants, along with the new markup.
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 is a method that takes two string arguments. The first being the insertion point relative to the node that
insertAdjacentHTML is invoked on:
afterend. The second argument is a string containing the HTML markup you want to add.
Here is a visualization of the position names:
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)
Was this found on MDN?
Hey, Peter! Yeah, the screenshots are pulled from MDN.