I gather that the whole point of a DocumentFragment is to be able to construct the contents without touching the DOM until it’s ready to go.
Given that DocumentFragment doesn’t support innerHTML
, it can be a bit tedious. On the other hand, once constructed, it’s easy to add the contents to an existing DOM node by the fragment itself.
If I create a div
without adding it to the DOM, I can populate it how I like, including innerHTML
. As far as I can tell, it should have no additional impact on performance.
Is there a simple way (ie in one line or so) to copy the contents of an existing DOM node to a DocumentFragment? The process would look like:
var div=document.createElement('div');
var fragment=document.createDocumentFragment();
div.innerHTML='…';
// copy contents to fragment
// etc
This way I could have the best of both worlds.
Answer
Here is the answer by @KevBot below incorporated into the example:
var divTest=document.querySelector('div#test');
var html='<p>One</p><p>Two</p>';
var fragment=document.createRange().createContextualFragment(html);
divTest.appendChild(fragment);