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);
Yes, you can easily create a fragment with a string of HTML using the document.createRange
method.
document.createRange
returns a Range
object, which has a method called createContextualFragment
which allows you to get a fragment from just HTML.
function fragmentFromString(strHTML) {
return document.createRange().createContextualFragment(strHTML);
}
let div = document.createElement('div');
div.innerHTML = '<p>Testing</p>';
let fragment = fragmentFromString(div.innerHTML);
console.log(fragment);
<div>
<p>Random Content</p>
</div>
Works in all major browsers and IE11.