liveBook · Manning

innerHTML

As explained in Secrets of the JavaScript Ninja, Second Edition

A DOM element property that gets or sets HTML markup as the serialized contents of an element.

Need to turn an HTML string into usable DOM nodes? Assign it to a temporary element’s innerHTML, then extract the parsed nodes. The markup may need cleanup and browser-required wrappers first. section 12.1.1

A reliable conversion follows these steps:

  • Make the string valid HTML, including expanding self-closing tags that HTML does not support in that form. section 12.1.1
  • Wrap elements in the containers browser parsing rules require; for example, options need a select. section 12.1.1
  • Set the temporary element’s innerHTML, then extract its child nodes. section 12.1.1
let div = (doc || document).createElement("div");
div.innerHTML = mapEntry[1] + htmlString + mapEntry[2]

See the innerHTML assignment used to place wrapped markup in a temporary div. section 12.1.1

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Details markup preprocessing, required wrappers, insertion, and node extraction without developing getter behavior.
Examples
Uses option elements and table markup, including a self-closing table tag, to illustrate parsing constraints.
What you can do after
Build a DOM-node list from an HTML string by preparing markup, wrapping it, and extracting parsed children.
How it connects
Connects HTML validity and container requirements to DOM nodes and DOM fragments.

Also explained in

Compare how 2 books explain innerHTML →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Second Edition. The section links point to the parts of the book it draws on.