Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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.