-1

Im a javascript beginner and this is my first project in school. Im trying to display an image with the title and so on but i just dont know how to add in the images into my array and display them.

const products = [
    { id: 1, title: "title", description: "description", price: 123},
    { id: 2, title: "title B", description: "description B", price: 456 },
    { id: 3, title: "title C", description: "description C", price: 789 },
];

function displayProducts() {
    let container = document.querySelector(".container");

    for (let product of products) {
        container.innerHTML +=
            `<div class="item">` +
            `<h2>${product.title}</h2>` +
            `<p>${product.description}</p>` +
            `<p>Pris: <b>${product.price}</b></p>` +
            `<button onclick="addToCart(${product.id})">Buy</button>`;
    }
}
  • All you need for the [` tag`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img) is a valid `src` URL – Phil Dec 07 '21 at 01:47

2 Answers2

2

Just add another index that takes in the image source/path as the value, and populates it inside a div, just like how you did for the title/description. For the path of the image you might want to add a relative/absolute path appropriately.

    const products = [
    { id: 1, title: "title", description: "description", price: 123, img: 'images/image1.jpeg'},
    { id: 2, title: "title B", description: "description B", price: 456, img: 'images/image3.jpeg' },
    { id: 3, title: "title C", description: "description C", price: 789, img: 'images/image3.jpeg' },
];

function displayProducts() {
    let container = document.querySelector(".container");

    for (let product of products) {
        container.innerHTML +=
            `<div class="item">` +
            `<h2>${product.title}</h2>` +
            `<p>${product.description}</p>` +
            `<p>Pris: <b>${product.price}</b></p>` +
            `<img src=${product.img} />
            `<button onclick="addToCart(${product.id})">Buy</button>`;
    }
}
Pbk1303
  • 3,702
  • 2
  • 32
  • 47
0
  function displayProducts() {
    let container = document.querySelector(".container");

    for (let product of products) {
        container.innerHTML +=
        `<div class="item">` +
        `<h2>${product.title}</h2>` +
        `<p>${product.description}</p>` +
        `<p>Pris: <b>${product.price}</b></p>` +
        `<p><img src="photoUrl.png" alt="photo" /></p>` +
        `<button onclick="addToCart(${product.id})">Buy</button>`;
   }
}
skyxfall
  • 1
  • 2