Search code examples
javascripthtmlappendappendchild

Append array of element in single DOM reflow


In JavaScript, the element.append() function accepts multiple parameters.

append(param1, param2, /* … ,*/ paramN)

I would like to append a set of elements in one time (for performance reason) to prevent reflow between call of el.append().

Here is a simple example:

HTML

<div id="parent"></div>

JavaScript

let parent = document.getElementById('parent');

let array=[];    
for (let i=0 ; i<10 ; i++) {
    array[i] = document.createElement("span");
    array[i].textContent = i;

    // Works OK
    //parent.append(array[i]);
}
    
// Does not work
document.getElementById('parent').append(array)

Here is the assocated JSFiddle: https://jsfiddle.net/Imabot/amd0txg6/

Is there a way to append a set of element created dynamically (for example an array) at once?


Solution

  • you have to spread the array:

    document.getElementById('parent').append(...array)
    

    jsfiddle