Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert array of elements into the DOM? [duplicate]

Tags:

javascript

dom

I have an array of elements:

const itemCurrent = document.createElement('div');
const itemNext = document.createElement('div');

Ive created an array of them:

const itemsAll = [itemCurrent, itemNext];

How can I insert all of them into the body of my page?

like image 308
Evanss Avatar asked Sep 20 '25 15:09

Evanss


1 Answers

You may simply use .append() to append multiple DOM nodes all at once as follows;

var divs = Array.from({length:10}) // lets make an array of 10 divs
                .map(function(_,i){
                       var el = document.createElement('div');
                       el.textContent = `I am div # ${i}`;
                       return el;
                     });
document.body.append(...divs);

In fact the above snippet has some redundany since Array.from() bears built in mapping. So the following rephrased code would be more reasonable.

var divs = Array.from( {length:10}     // lets make an array of 10 divs
                     , function(_,i){  // and map it accordingly
                          var el = document.createElement('div');
                          el.textContent = `I am div # ${i}`;
                          return el;
                       } 
                     );
document.body.append(...divs);
like image 160
Redu Avatar answered Sep 22 '25 08:09

Redu