liveBook · Manning

Html wrapping

As explained in Secrets of the JavaScript Ninja, Second Edition

The technique of surrounding HTML markup with required container markup before parsing or insertion.

Some HTML fragments need specific ancestor elements to parse correctly. Wrapping a fragment in its required markup before assigning it to innerHTML supplies that context. section 12.1.1

A wrapper map associates fragment tags with the markup needed to parse them:

  • Place <option> and <optgroup> inside <select multiple>. section 12.1.1
  • Place table-related elements such as <tr>, <td>, and <th> inside the required table structure. section 12.1.1

Extracting nodes

A getNodes helper selects a wrapper from the fragment’s first tag, assigns the wrapped string to a div’s innerHTML, then descends through the wrapper to return the fragment’s child nodes. section 12.1.1

Table 12.1. Elements that need to be contained within other elements (view table figure)

Element name

Ancestor element

<option>, <optgroup> <select multiple>...</select>
<legend> <fieldset>...</fieldset>
<thead>, <tbody>, <tfoot>, <colgroup>, <caption> <table>...</table>
<tr> <table><thead>...</thead></table>
<table><tbody>...</tbody></table>
<table><tfoot>...</tfoot></table>
<td>, <th> <table><tbody><tr>...</tr></tbody></table>
<col> <table>
<tbody></tbody>
<colgroup>...</colgroup>
</table>

Browse the element-to-ancestor mapping for the required wrappers. section 12.1.1

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Explains required ancestors, compares insertion strategies, and demonstrates wrapper mapping and node extraction.
Examples
Uses option elements inside select and table elements inside their required table structures.
What you can do after
Build a DOM-node extraction helper that wraps fragments in required ancestors before assigning innerHTML.
How it connects
Connects HTML wrapping to innerHTML, DOM node creation, and HTML container semantics.

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.