liveBook · Manning

HTML string

As explained in Secrets of the JavaScript Ninja, Second Edition

A text representation of HTML markup that can be parsed into a document structure.

An HTML string is markup held as text, ready to be turned into DOM nodes. It’s useful for dynamic pages that insert client-side templates or HTML returned by a server. section 12.1

To convert a string into DOM nodes:

  • Check that the markup is valid HTML; normalize self-closing syntax for elements that do not support it. section 12.1.1
  • Wrap elements in containers required by HTML rules, such as placing <option> elements inside <select>. section 12.1.1
  • Set the wrapped string as the innerHTML of a temporary element, then extract the created nodes. section 12.1.1

Markup that needs context

A string containing standalone <option> elements or a self-closing <table/> needs adjustment before parsing: options need a select container, and table is not among HTML’s self-closing elements. section 12.1.1

$(document.body).append("<div><h1>Greetings</h1><p>Yoshi here</p></div>")

A jQuery append call shows the concise alternative: pass an HTML string directly for insertion. section 12.1

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Works through validation, wrappers, innerHTML parsing, and node extraction, while treating efficient insertion as a separate step.
Examples
Uses dynamic HTML insertion, standalone option elements, and self-closing table markup as examples.
What you can do after
Build it from scratch by validating markup, adding required wrappers, parsing with innerHTML, and extracting nodes.
How it connects
Connects HTML strings to the DOM, innerHTML, DOM fragments, and jQuery-based insertion.

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.