Appending fragments to the DOM instead of every node.


/ Published in: JavaScript
Save to your folder(s)



Copy this code and paste it in your HTML
  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. }

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.