skip to Main Content

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?

4

Answers


  1. you have to spread the array:

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

    jsfiddle

    Login or Signup to reply.
  2. if you want to append a set of element created dynamically (for example an array) at once you can use append() from jQuery

    Login or Signup to reply.
  3. You can use a document fragment.

    Since the document fragment is in memory and not part of the main DOM tree, appending children to it does not cause page reflow (computation of element’s position and geometry). Historically, using document fragments could result in better performance.

    const parent = document.getElementById('parent');
    
    const frag = document.createDocumentFragment();
    
    for (let i = 0; i < 10; i++) {
      const span = document.createElement('span');
      span.textContent = i;
      frag.append(span);
    }
        
    parent.append(frag);
    <div id="parent"></div>
    Login or Signup to reply.
  4. Alternatively, you can make use of a fragment to avoid reflow on multiple insertions. For instance,

    const fragment = document.createDocumentFragment();
    
    for (let i = 0; i < 10; i++) {
      const span = document.createElement('span');
      span.textContent = i;
      fragment.appendChild(span);
    }
    
    document.getElementById('parent').appendChild(fragment);
    <div id="parent"></div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search