Skip to content

Instantly share code, notes, and snippets.

@jonathantneal
Last active September 5, 2022 09:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonathantneal/d3ce9f23edb1567cbd5d9d72298d7e0f to your computer and use it in GitHub Desktop.
Save jonathantneal/d3ce9f23edb1567cbd5d9d72298d7e0f to your computer and use it in GitHub Desktop.
Create Fragment

Create Fragment

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.

createFragment = (range => {
range.selectNodeContents(range.createContextualFragment('<template>').lastChild)
return range.createContextualFragment.bind(range)
})(new Range())
@Krutsch
Copy link

Krutsch commented Sep 13, 2020

Cool. I always sticked with:

const createFragment = document
    .createRange()
    .createContextualFragment.bind(document.createRange());

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>.

@artydev
Copy link

artydev commented Sep 5, 2022

Thank you Jonathan.
I have published your tips on DevTo
Hope you don't mind
Regards

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment