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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With