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.
You can create a <template>
element, which is a document fragment; set .innerHTML
of template
element, and get .innerHTML
of template
element using .content
property
var template = document.createElement("template");
var div = document.createElement("div");
div.innerHTML = "<p>abc</p>";
template.innerHTML = div.innerHTML;
document.body.appendChild(template.content);
You can use appendChild
to add the new element to the fragment.
var div=document.createElement('div');
var fragment=document.createDocumentFragment();
div.innerHTML='…';
fragment.appendChild(div);
If you only want to inject the contents of the element into the fragment then you can iterate over the childNodes
and insert them into the fragment.
div.childNodes.forEach(function(node) {
fragment.appendChild(node);
});
Try these out for size
text = frag.appendChild( document.createTextNode( "insert text here" ) )
or
text = frag.appendChild( document.createTextNode( div.innerHTML ) )
or
text = frag.appendChild( document.createTextNode( div.textContent ) )
The text
variable will hold the textnode while you have also appended the textnode all in one line
来源:https://stackoverflow.com/questions/41774889/javascript-copy-node-to-documentfragment