I am trying to take an array and wrap 3 items at a time in a row and append it to the DOM/container. I've found a lot of examples using jquery however I need vanilla js solution. If there is a better/simpler way I am all ears but I am having a rough go with this one. The closest I have managed to get is the last image in each group of three to display
example of what I am trying to do:
arr = [1,2,3,4,5,6,7,8,9]
output
<div class="track">
<div class="track__block">
<figure>1<figure>
<figure>2<figure>
<figure>3<figure>
</div>
</div>
<div class="track">
<div class="track__block">
<figure>4<figure>
<figure>5<figure>
<figure>6<figure>
</div>
</div>
<div class="track">
<div class="track__block">
<figure>7<figure>
<figure>8<figure>
<figure>9<figure>
</div>
</div>
My Attempt:
// Create a function to group items by 3
function chunkArray (arr, size) {
const results = []
while (arr.length) {
results.push(arr.splice(0, size))
}
return results
}
const groupedTeam = chunkArray(arr, 3)
// returns [{1,2,3}, {4,5,6}, {7,8,9}]
// Create the rows and append to the DOM
for (let i = 0; i < groupedTeam.length; i++) {
const row = document.createElement('div')
row.classList.add('track')
const block = document.createElement('div')
block.classList.add('track__block')
container.appendChild(row)
row.appendChild(block)
}
// This creates the correct number of rows on the DOM
<div class="track">
<div class="track__block"></div>
</div>
<div class="track">
<div class="track__block"></div>
</div>
<div class="track">
<div class="track__block"></div>
</div>
// Wrap the array items in a figure and place into the rows by threes
// This is the part I can't get right
const blocks = [...document.querySelectorAll('track__blocks')]
for (let i = 0; i < blocks.length; i++) {
for (let x = 0; x < groupedTeam[i].length; x++) {
let memberContainer =
`
<figure class="track track__block grid grid--team__track__block">
<img class="image image--lazy image--w320 track__block grid--team__track__block--image" src=
"imgs/image-${groupedTeam[i][x]}" />
</figure>
`
blocks[i].innerHTML = memberContainer
}
}