The createFragment
function returns an HTML fragment from a string.
[
{ name: 'Hedral', coat: 'Tuxedo', legs: 4 },
{ name: 'Pillar', coat: 'Ticked Tabby', legs: 3 },
].reduce(
(table, { name, coat, legs }) => {
const tr = createFragment(`<tr><td><td><td>`)
const [ nameTd, coatTd, legsTd ] = tr.firstChild.children
nameTd.textContent = name
coatTd.textContent = coat
legsTd.textContent = legs
table.lastChild.append(tr)
return table
},
createFragment(`<table><thead><th>Name<th>Coat<th>Legs<tbody>`).firstChild
) /* outerHTML:
<table>
<thead>
<tr><th>Name</th><th>Coat</th><th>Legs</th></tr>
</thead>
<tbody>
<tr><td>Hedral</td><td>Tuxedo</td><td>4</td></tr>
<tr><td>Pillar</td><td>Ticked Tabby</td><td>3</td></tr>
</tbody>
</table> */
Fragments created with createFragments
have no conformance requirements. Usually, fragments generated with createContextualFragment
leave out elements that are not already supported as direct descendants of <body>
, such as <tr>
or <thead>
. The createFragment
function works around this limitation by defining the context of the createContextualFragment
function as being a <template>
element, which has no conformance requirements.
Cool. I always sticked with:
but just as you mentioned, there were flaws with
<colgroup>
,<tbody>
,<tfoot>
,<thead>
and<tr>
.Nevertheless, both approaches do not create the following elements:
<html>
,<body>
and<head>
.