← Back to HTML & CSS, page 8

html-css-0157 · Medium mid

How do innerHTML, insertAdjacentHTML and DOMParser differ, and what happens to scripts and context?

innerHTML replaces all children and parses in the context of the element, insertAdjacentHTML adds markup at a position without touching existing nodes, and DOMParser builds a separate inert document. Scripts do not run through innerHTML, but event handler attributes do, so untrusted markup stays dangerous.

Full answer

Three APIs turn a string into DOM nodes. They differ in where the nodes go and in what the parser is allowed to do.

el.innerHTML = html replaces all children of el. The string is parsed in the context of that element, so the rules depend on it. A tr assigned to a div is dropped, because a div is not a place where rows are allowed. Scripts inserted this way do not run, but event handler attributes such as onerror do run. That is why innerHTML with untrusted text is dangerous. Replacing all children also removes event listeners that were on the old nodes, and it parses the whole string again each time.

el.insertAdjacentHTML(position, html) parses the string and adds it at one of four places without touching the existing children: beforebegin, afterbegin, beforeend and afterend. It is the right tool to append markup, and it does not rebuild the old content, so listeners on the existing nodes stay.

new DOMParser().parseFromString(html, "text/html") makes a separate, inert document. Nothing in it runs. Images do not load and scripts do not execute. You can read it with querySelector, for example to pull a fragment from a server response. Then you import the nodes you want with document.importNode. This is a good way to inspect markup safely, but the result is not safe to insert unless the content is sanitized.

Related: a template element holds parsed, inert content for later cloning, and createContextualFragment parses in a given context and does run scripts.

The new element is added after the old one, and the old one is untouched. The row string is dropped when parsed inside a div, but it stays when parsed inside a tbody. The script string did not run. The parsed document gave back the text of its b element.

Use textContent when the data is plain text, and a sanitizer when it is real markup from outside.

html
<div id="host"><span id="old">old</span></div>
<table id="tb"><tbody id="body"></tbody></table>
<script>
  window.ran = 0;
  host.insertAdjacentHTML("beforeend", "<b id='b'>new</b>");
  const probe = document.createElement("div");
  probe.innerHTML = "<tr><td>x</td></tr><script>window.ran++<\/script>";
  window.rowsInDiv = probe.querySelectorAll("tr").length;
  body.innerHTML = "<tr><td>x</td></tr>";
  window.parsed = new DOMParser().parseFromString("<p><b>bold</b></p>", "text/html").querySelector("b").textContent;
</script>

Checked in Chrome 156 only. The unsafe case is run on purpose in a test page. Never do this with real user data. Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.

Key points

  • innerHTML replaces children and drops their listeners.
  • insertAdjacentHTML appends at four positions.
  • DOMParser makes an inert document.
  • Parsing depends on the context element.
  • Handler attributes still run; sanitize untrusted markup.

Common mistakes

  • Using innerHTML to append items in a loop, which re-parses and removes listeners.
  • Expecting a tr string to work when assigned to a div.
  • Treating a DOMParser result as safe to insert without sanitizing.

Follow-ups

  • Why does a tr string disappear when assigned to a div?
  • When would you use a template instead?

Tips

  • Explain the difference in where nodes go and what is replaced.
  • Say that scripts do not run through innerHTML but handler attributes do.