6

I have to create seven div elements in one hit - container A which contains A1, A2, A3 & A4, and then A2a & A2b within A2. I am using multiple calls to this little function:

function u1(t,i,c,p){ // type,id,class_name,parent_id
    var tag=document.createElement(t); // Create node to be appended
    tag.id=i;
    tag.className=c;
    document.getElementById(p).appendChild(tag);
}

My question: Is there is a more time-efficient way to bundle the seven together, and then just do one DOM append? Or is innerHTML a good option?

Thanks :)

Nick
  • 5,995
  • 12
  • 54
  • 78
  • 5
    If you have to comment your code to explain what your function parameters are then you've named them badly. – Anthony Grist Mar 07 '12 at 09:42
  • 1
    Point taken. I don't need to name them, really. The original code had the full names, and I just cut and pasted when I was tidying. BTW, I'm not sure you'll feel so fired up about it in 20 years :) – Nick Mar 07 '12 at 10:32

1 Answers1

11

You could just use .innerHTML. An alternative would be to use a document fragment:

var fragment = document.createDocumentFragment();

function u1(t, i, c){ // type,id,class_name
    var tag = document.createElement(t); // Create node to be appended
    tag.id = i;
    tag.className = c;
    fragment.appendChild(tag); // will use `fragment` from the outer scope
}

// call u1() seven times

// then insert all the elements into the DOM all at once
document.getElementById('foo').appendChild(fragment);

Document fragments are a bit slow to create, but can save performance in the long run. In this case, for example, you go from 7 DOM insertions to just one. (Anything involving the DOM is slow in JavaScript.)

If you want to benchmark your specific use case using both approaches, create a jsPerf test case.

Mathias Bynens
  • 144,855
  • 52
  • 216
  • 248
  • 3
    +1 from me before the `.innerHTML` police arrive ;-) I'd go with the document fragment approach, regardless. – Andy E Mar 07 '12 at 09:57
  • 1
    You should add that the slowest in JS is DOM manipulation (not taking into account the re-rendering). This is why adding only one node will be faster than seven, even if they're smaller. – Florian Margaine Mar 07 '12 at 10:22
  • Thanks for all this, not least the jsPerf lead. I'd been wondering how I can benchmark stuff recently. I appreciate the help :) – Nick Mar 07 '12 at 10:37
  • @MathiasBynens - I can't get a nested fragment working! I can create a fragment, append children and add it to the DOM. But how do I add children to the children within the fragment? – Nick Mar 08 '12 at 20:17
  • For anyone in the future: the answer to the nesting question in my last comment is here: http://stackoverflow.com/questions/9652420/inserting-a-nested-div-structure-with-createdocumentfragment :) – Nick Mar 11 '12 at 06:58
  • For those who are interested, see the test case: http://jsperf.com/innerhtml-rdc2 The fragment wins hands down. – Nick Mar 12 '12 at 10:45