I am trying to create a grid using forEach
. What i am after is to be able to wrap items into rows of 3. How would i do that?
Here’s my current code:
this.el = document.getElementById('feed')
const releases = data.Releases //array of items
const list = document.createDocumentFragment()
releases.forEach((release, index) => {
let item = document.createElement('div')
let a = document.createElement('a')
let title = document.createElement('h2')
let date = document.createElement('time')
title.innerHTML = `${release.Title}`
date.innerHTML = `${release.PublishDate}`
a.setAttribute('href', release.EncryptedId)
a.appendChild(date)
a.appendChild(title)
item.appendChild(a)
list.appendChild(item)
})
this.el.appendChild(list)
Expected output:
<div id="feed">
<div>
<div><a href="">1<h2></h2><time></time></a></div>
<div><a href="">2<h2></h2><time></time></a></div>
<div><a href="">3<h2></h2><time></time></a></div>
</div>
<div>
<div><a href="">4<h2></h2><time></time></a></div>
<div><a href="">5<h2></h2><time></time></a></div>
<div><a href="">6<h2></h2><time></time></a></div>
</div>
</div>
2
Answers
a new row is created every time the index is divisible by 3. This row is then appended to the list. The items are appended to the last row in the list. The ‘row’ variable keeps track of the current row.
Change the structure of your data based on how you need it to be. In this case you’ll want something that resembles the following structure:
So you’ll have to divide your array in to chunks of 3. You can write a function for this which does just that. Here’s one for example:
Apply that to your data and loop over the nested array. In the outer loop, create a
div
which. Then in the inner loop, create the rest of the elements and append them to thediv
. Then append thediv
to thelist
.