If you create a DocumentFragment using document.createDocumentFragment(), append children to it, then append the buffer to something, all the children of the buffer seem to disappear. Example:
var buffer = document.createDocumentFragment() ;
for (var i = 1; i <= 10; i++)
{
var div = document.createElement('div');
div.innerHTML = i;
buffer.appendChild(div);
}
console.log( 'buffer: ' , buffer );
document.getElementById('container').appendChild(buffer);
console.log( 'buffer now: ' , buffer );
Here, in the first console.log, the buffer’s childNodes has 10 children, in the second, childNodes has 0.
Is there a way to retain the childnodes somewhere and not have them reset, in order to cache the buffer and not have to append children to it each time?
You’ve just described the nature of a
DocumentFragment. If you want to reuse the same contents, you could clone the fragment before appending it to the document each time: