I have seen a few different methods to add elements to the DOM. The most prevelent seem to be, for example, either
document.getElementById(\'foo\').innerHTM
Though this is an old thread, one thing that is not mentioned is the while innerHTML
can be faster, care should be taken. Using innerHTML
will render every child of the modified element, old and new alike. As such, one single innerHTML
assignment is faster (slightly) than DOM create/append, but multiple innerHTML
will definetly be slower.
For example:
for(let i=0; i < 10; i++)
document.body.innerHTML+='some text';
will be nearly nearly 5x slower than
let html = '';
for(let i=0; i < 10; i++)
html += 'some text';
document.body.innerHTML = html;
Since innerHTML
assignment is letting the browser natively create/append elements, the second methods results in 10 elements being natively created/appended, while the firstmethod results in 55 elements being created/appended (and 45 being destroyed): 1 element created on first loop-iteration, 2 elements created on the second loop-iteration (the original being destroyed), 3 elements created on the third loop-iteration (the previous 2 being destroyed), and so on.
If you use innerHTML
for speed, you must make sure to create the entire html string first before making the innerHTML
assignment, such as creating fresh DOM containers/elements. innerHTML
, on the other hand, is a performance loser when appending any container with existing childNodes, especially those with large number of childNodes.