DEV Community 👩‍💻👨‍💻

artydev
artydev

Posted on

Returning HTML Fragment from String

Here is a very nice way to perform this action.
Thanks to Jonathan Neal

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

Enter fullscreen mode Exit fullscreen mode
[
  { 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
)

Enter fullscreen mode Exit fullscreen mode

Yuou can test it here CreateFragment

Top comments (0)

Visualizing Promises and Async/Await 🤯

async await

☝️ Check out this all-time classic DEV post