I'm trying to render objects that are in an array into my DOM. I'm trying to display each object in its own card for viewing (using Tailwind css). I'm fairly new to coding so I feel like it's something very simple that I'm overlooking here. Any help would be greatly aprpeciated!
const productsDOM = document.querySelector(`.products`);
const itemObject = [{
title: "Chocolate",
price: 10.99,
id: 1,
img: "https://images.pexels.com/photos/1055272/pexels-photo-1055272.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260"
}, {
title: "Whipped Cream",
price: 12.99,
id: 2,
img: "https://images.pexels.com/photos/1055270/pexels-photo-1055270.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=750&w=1260"
}, {
title: "White Frosting",
price: 12.99,
id: 3,
img: "https://images.pexels.com/photos/1055271/pexels-photo-1055271.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260"
}, {
title: "Berry",
price: 14.99,
id: 4,
img: "https://images.pexels.com/photos/3081657/pexels-photo-3081657.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260"
}, {
title: "Deluxe",
price: 19.99,
id: 5,
img: "https://images.pexels.com/photos/1998634/pexels-photo-1998634.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260"
}, {
title: "Oreo",
price: 14.99,
id: 6,
img: "https://images.pexels.com/photos/783274/pexels-photo-783274.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260"
}];
function displayProducts() {
let html = ``;
itemObject.forEach(() => {
html += `
<div id="item-1" class="bg-white rounded-lg">
<img class="rounded-md w-screen object-cover max-h-60"
src="${itemObject.img}"
alt="">
<div class="py-2 px-8 text-gray-600">
<div class="grid grid-cols-2 py-3 text-xl font-bold ">
<h3>${itemObject.title}</h3>
<p class="text-right">$${itemObject.price}</p>
</div>
<button data-id=${itemObject.id}
class="bg-purple-200 font-bold px-3 mt-2 text-xl py-4 w-full rounded-md transition-all hover:bg-purple-300">Purchase</button>
</div>
</div>
`;
});
productsDOM.innerHTML = html;
}
displayProducts. Also,idattributes should have unique values... you cannot all give themid="item-1".