Domenic Domenic - 1 year ago 61
Javascript Question

Inserting arbitrary HTML into a DocumentFragment

I know that adding

to document fragments has been recently discussed, and will hopefully see inclusion in the DOM Standard. But, what is the workaround you're supposed to use in the meantime?

That is, take

var html = '<div>x</div><span>y</span>';
var frag = document.createDocumentFragment();

I want both the
and the
inside of
, with an easy one-liner.

Bonus points for no loops. jQuery is allowed, but I've already tried
is still empty afterward.

Answer Source

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 IE11 to the mix:

function fragmentFromString(strHTML) {
    return document.createRange().createContextualFragment(strHTML);

The coverage is better than the <template> method and tested ok in IE11, Ch, FF.

Live test/demo available