Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript Interactive Web Pages with JavaScript Traversing and Manipulating the DOM with JavaScript Perform: Appending and Removing Elements

Sergi Oca
Sergi Oca
7,981 Points

Is documentFragment a better approach to appending multiple items?

I'm not sure if it's not mentioned in the video because it's not so important or if it is mentioned later on, but when he created multiple listItem.appendChild, it didn't felt right to me. Searching around a bit I found the document.createDocumentFragment() method.

Is this a better approach to appending multiple childs to an element?

    var createNewTaskElement = function( taskString ) {


    //Create list item
     var listItem = document.createElement("li");


     //input (checkbox)
       var checkBox = document.createElement("input");

    //label
      var label = document.createElement("label");

     //input (text)
      var editInput = document.createElement("input");

     //button.edit
      var editButton = document.createElement("button");

     //button.delete
      var deleteButton = document.createElement("button");

      var frag = [checkBox, label, editInput, editButton, deleteButton];

      var docFrag = document.createDocumentFragment();
       for ( var i = 0; i < frag.length; i++ ) {
          docFrag.appendChild(frag[i]);
       } 

      listItem.appendChild(docFrag);

So we only append one "docFrag" element instead of 6.

1 Answer

Bryan Peters
Bryan Peters
11,996 Points

I believe you are correct - in my experience, page performance is much better when you can perform a single DOM writes instead of multiple DOM writes, and documentFragment is a handy way to do so. My guess is that this is being used to introduce how you can append elements to the DOM, not an endorsement of appending individual form elements / table rows as best practice.