using document.createDocumentFragment() and innerHTML to manipulate a DOM
While DocumentFragment
does not support innerHTML
, <template>
does.
The content
property of a <template>
element is a DocumentFragment
so it behaves the same way. For example, you can do:
var tpl = document.createElement('template');
tpl.innerHTML = '<tr><td>Hello</td><td>world</td></tr>';
document.querySelector('table').appendChild(tpl.content);
The above example is important because you could not do this with innerHTML
and e.g. a <div>
, because a <div>
does not allow <tr>
elements as children.
NOTE: A DocumentFragment
will still strip the <head>
and <body>
tags, so it won't do what you want either. You really need to create a whole new Document
.
You can't set the innerHTML of a document fragment like you would do with a normal node, that's the problem. Adding a standard div and setting the innerHTML of that is the common solution.