user1637281
user1637281

Reputation:

Does a documentFragment element reset itself?

This is a strange behavior I noticed. I did not reset a document but immediately used it after I had appended it, and the previous elements it contained were not there.

Should I be clearing it as such?

frag_inner = '';

Are there side-effects I'm not aware of?

frag_outer = NS.createDocumentFragment();
frag_inner = NS.createDocumentFragment();

NS.eachIndex(obj, function(val) {

    // fragment element - inner

    // image element

    val.view_picture = (val.picture === '0') ? this.A.images + 'generic_large.jpg' :
            this.A.pictures + val.h_file  + '-2.jpg';
    img_element = $A.createElement('img');
    img_element.className = 'tweet';
    img_element.src = val.view_picture;
    frag_inner.appendChild(img_element);

    // link element

    link_element = $A.createElement('a');
    link_element.className = 'tweet';
    link_element.innerHTML = val.name + ' posted ' +
            this.prettyTime(val.time) + '<br>';
    frag_inner.appendChild(link_element);

    // paragraph element

    par_element = $A.createElement('p');
    par_element.className = 'tweet';
    par_element.innerHTML = val.tweet;
    frag_inner.appendChild(par_element);

    // div element

    div_element = $A.createElement('div');
    div_element.className = 'tweet';
    div_element.appendChild(frag_inner);

    // append the div which is now populated

    frag_outer.appendChild(div_element);

}, this);

Upvotes: 0

Views: 276

Answers (1)

raina77ow
raina77ow

Reputation: 106365

I think it's actually the expected behaviour, as...

1) it's a well-known feature of Node.appendChild to move existing Nodes. As said in the docs (MDN)...

[Node.appendChild]... adds a node to the end of the list of children of a specified parent node. If the node already exists it is removed from current parent node, then added to new parent node.

2) when you append documentFragment, you actually append all its children (MDN again):

Various other methods can take a document fragment as an argument (e.g., any Node interface methods such as Node.appendChild and Node.insertBefore), in which case the children of the fragment are appended or inserted, not the fragment itself.

The point is, when you do someNode.append(documentFragment), you remove all its children from it, then append them to someNode. That's why documentFragment is empty as result.


Note that when you do this...

frag_inner = '';

... you're not clearing the documentFragment stored in this variable - you store a new value (an empty string, obviously) in it instead. The very first attempt to work with it as with documentFragment should result in something like TypeError: Object has no method 'appendChild'.

Upvotes: 2

Related Questions