DEV Community

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

Posted on • Updated on

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.

Discussion (0)