DEV Community

Cover image for Creating A Document Fragment
bob.ts
bob.ts

Posted on • Edited on

2

Creating A Document Fragment

On a recent project, using Vanilla-JS, I was looking to simplify the general coding patterns I've used for years. I was taking an array of content and converting it to a longer string for inclusion on the DOM.

For example ...

var html = [
  '<div>First</div>',
  '<div>Second</div>',
  '<div>Third</div>'
].join('');
Enter fullscreen mode Exit fullscreen mode

While this pattern works, to some degree, if there is any nesting it can get rather tedious to deal with.

Template Literal

HTML Template

Wrapping Up

So, here we can see a clear pattern to allow for content to be created and appended as a child to some element.

What is not included is how the string gets converted into an HMTL fragment ...

function fragmentFromString (stringHTML) {
  let temp = document.createElement('template');
  temp.innerHTML = stringHTML;
  return temp.content;
}
Enter fullscreen mode Exit fullscreen mode

This solution came from the following ...

Here is a way in modern browsers without looping:

var temp = document.createElement('template');
temp.innerHTML = '<div>x</div><span>y</span>';

var frag = temp.content;

or, as a re-usable

function fragmentFromString(strHTML) {
    var temp = document.createElement('template');
    temp.innerHTML = strHTML;
    return temp.content;
}

UPDATE I found a simpler way to use Pete's main idea, which adds…

Adding The Document Fragment To The DOM

The final step is pretty straight forward; using .appendChild to a DOM element allows the fragment to be placed into the DOM.

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay