Posted By

iTony on 07/21/08


Tagged

DOM append documentfragment fragment


Versions (?)

Who likes this?

4 people have marked this snippet as a favorite

romanos
rafael
ShadowKing
wizard04


Appending fragments to the DOM instead of every node.


 / Published in: JavaScript
 

URL: http://ejohn.org/blog/dom-documentfragments/

  1. var elems = [
  2. document.createElement("hr"),
  3. text( document.createElement("b"), "Links:" ),
  4. document.createTextNode(" "),
  5. text( document.createElement("a"), "Link A" ),
  6. document.createTextNode(" | "),
  7. text( document.createElement("a"), "Link B" ),
  8. document.createTextNode(" | "),
  9. text( document.createElement("a"), "Link C" )
  10. ];
  11.  
  12. function text(node, txt){
  13. node.appendChild( document.createTextNode(txt) );
  14. return node;
  15. }
  16.  
  17. // append fragment instead of all the nodes.
  18. var div = document.getElementsByTagName("div");
  19.  
  20. var fragment = document.createDocumentFragment();
  21. for ( var e = 0; e < elems.length; e++ ) {
  22. fragment.appendChild( elems[e] );
  23. }
  24.  
  25. for ( var i = 0; i < div.length; i++ ) {
  26. div[i].appendChild( fragment.cloneNode(true) );
  27. }

Report this snippet  

You need to login to post a comment.