I figured it out. I had to put the template and the copytemplate within the map function for it to work.
Solution 1 :
Problem :
This is my first time working with the html template tag. I don’t know if I am doing it wrong but the output of the template is only showing the last item in the array. I’ve tried to loop through it and the foreach method but still only the last item shows. I know I am probably overriding the items as they are stacked on top of each other but I can’t seem to figure it out Can someone point me in the right direction?
<div class="products-container">
<template>
<div class="product">
<img class="img">
<h2 class="item-title"></h2>
<h3 class="price"></h3>
</div>
</template>
</div>
const template = document.querySelector('template').content
const copyTemplate = document.importNode(template, true)
let shoppingList = [];
async function getData(data) {
const products = data.items.map(product => {
copyTemplate.querySelector('.item-title').textContent = product.title;
copyTemplate.querySelector('.price').textContent = product.price;
copyTemplate.querySelector('.img').src = product.image;
});
document.querySelector('.products-container').appendChild(copyTemplate);
shoppingList.push(products);
return products
}
Comments
Comment posted by Karan Singh
you have to append the item as you map through it…..bcz if you will continue to map through it you will reach the end of the array….so just add the 3rd last line { document.querySelector(‘.products-container’).appendChild(copyTemplate); } into the map function and it will work.
Comment posted by Alanaj
@KaranSingh Hi, that doesn’t work. Now, it only returns the first item in the array