Ali
Ali

Reputation: 267077

document.createDocumentFragment() seems to get emptied after being appended?

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?

Upvotes: 2

Views: 425

Answers (1)

Tim Down
Tim Down

Reputation: 324587

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:

var bufferCopy = buffer.cloneNode(true);
document.getElementById('container').appendChild(bufferCopy);

Upvotes: 1

Related Questions