Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Speed/efficiency of multiple DOM appendChild

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 :)

like image 514
Nick Avatar asked Mar 07 '12 09:03

Nick


People also ask

Can appendChild take multiple arguments?

appendChild() returns the newly appended node, or if the child is a DocumentFragment , the emptied fragment. Note: Unlike this method, the Element.append() method supports multiple arguments and appending strings. You can prefer using it if your node is an element.

What does appendChild () method perform?

The appendChild() method of the node interface, is used to create a text node as the last child of the node. This method is also used to move an element from one element to another element.

Is innerHTML faster than createElement?

#1) createElement is more performant In other words, creating a new element and appending it to the DOM tree provides better performance than the innerHTML .

What is the difference between innerHTML and appendChild?

Answer : appendChild is used to insert new node in DOM. innerHTML is a property of DOM that allows to replace content of an element with different HTML, which automatically gets parsed into DOM nodes.


1 Answers

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.

like image 122
Mathias Bynens Avatar answered Oct 27 '22 05:10

Mathias Bynens