skip to Main Content

I have this data that returns a url of an image.

  1. How can I insert it into my card, this is what I have for now

  2. How can I set the URL in the "src" of my image. Thank you.

    Card 1

    Some text

     <div class="column">
         <div class="card">
             <h3 class="title">Card 2</h3>
             <img class="image" src="image">
             <p class="price">Some text</p>
         </div>
     </div>
    
     <div class="column">
         <div class="card">
             <h3 class="title">Card 3</h3>
             <img class="image" src="image">
             <p class="price">Some text</p>
         </div>
     </div>
    

My script here

<script>
    const jsonArray = '[{"product_id": 1,"product_name": "Product 1","product_image": "https://www.gstatic.com/webp/gallery3/1.sm.png","product_price": 19.99},{"product_id": 2,"product_name": "Product 2","product_image": "https://www.gstatic.com/webp/gallery3/1.sm.png","product_price": 24.99},{"product_id": 3,"product_name": "Product 3","product_image": "https://www.gstatic.com/webp/gallery3/1.sm.png","product_price": 29.99}]';
    const data = JSON.parse(jsonArray);

    const cardElements = document.getElementsByClassName("card");

    for (var i = 0; i < data.length; i++) {
        const currentCardElement = cardElements.item(i);

        const cardTitle = currentCardElement.getElementsByClassName("title").item(0);
        cardTitle.innerHTML = data[i].product_name;

        const cardImage = currentCardElement.getElementsByClassName("image").item(0);
        cardImage.innerHTML = data[i].product_image;

        const cardPrice = currentCardElement.getElementsByClassName("price").item(0);
        cardPrice.innerHTML = data[i].product_price;
    }
</script>

4

Answers


  1. If I understand your question correctly you want to set the src attribute of <img> to an image received with the data?

    W3Schools shows up pretty fast with the right search. You might be looking for something like this.

    <!DOCTYPE html>
    <html>
    <body>
    
    <img id="myImage" src="smiley.gif">
    
    <script>
    document.getElementById("myImage").src = "landscape.jpg";
    </script>
    
    </body>
    </html>  
    
    Login or Signup to reply.
  2. You can use the setAttribute method on a DOM element to change its attribute, in this case src.

    Here is an example: After 3 seconds the dog will turn into a cat as its source gets replaced.

    setTimeout(() => {
      document.querySelector("img").src = "https://placekitten.com/300/300"
    }, 3000)
    <img src="https://placedog.net/300/300" id="img">

    In order to insert elements, you use several different functions to create and append an item. Here is an example:

    let node = document.createElement("p")
    let text = document.createTextNode("This paragraph was inserted with DOM!")
    node.appendChild(text)
    document.querySelector("#target").appendChild(node)
    <div id="target">
    
    </div>

    appendChild will always put an element at the end, but you can also put it in a different spot or move it with other functions.

    P.S. If you find this too tedious, using external libraries like jQuery or React can help make inserting and manipulating HTML much easier

    Login or Signup to reply.
  3. You can use setAttribute instead of innerHTML, i’ve removed the src from the HTML code since isn’t needed:

    const jsonArray = '[{"product_id": 1,"product_name": "Product 1","product_image": "https://www.gstatic.com/webp/gallery3/1.sm.png","product_price": 19.99},{"product_id": 2,"product_name": "Product 2","product_image": "https://www.gstatic.com/webp/gallery3/2.sm.png","product_price": 24.99},{"product_id": 3,"product_name": "Product 3","product_image": "https://www.gstatic.com/webp/gallery3/3.sm.png","product_price": 29.99}]';
    const data = JSON.parse(jsonArray);
    
    const cardElements = document.getElementsByClassName("card");
    
    for (var i = 0; i < data.length; i++) {
      const currentCardElement = cardElements.item(i);
    
      const cardTitle = currentCardElement.getElementsByClassName("title").item(0);
      cardTitle.innerHTML = data[i].product_name;
    
      const cardImage = currentCardElement.getElementsByClassName("image").item(0);
      cardImage.setAttribute("src", data[i].product_image); // Using setAttribute instead of innerHTML
    
      const cardPrice = currentCardElement.getElementsByClassName("price").item(0);
      cardPrice.innerHTML = data[i].product_price;
    }
    <div class="column">
      <div class="card">
        <h3 class="title">Card 2</h3>
        <img class="image">
        <p class="price">Some text</p>
      </div>
    </div>
    
    <div class="column">
      <div class="card">
        <h3 class="title">Card 3</h3>
        <img class="image">
        <p class="price">Some text</p>
      </div>
    </div>
    
    <div class="column">
      <div class="card">
        <h3 class="title">Card 3</h3>
        <img class="image">
        <p class="price">Some text</p>
      </div>
    </div>
    Login or Signup to reply.
  4. You should assign the src attribute of the image to the URL, not the innerHTML. Here’s how you can modify your script to do so:

    <script>
        const jsonArray = '[{"product_id": 1,"product_name": "Product 1","product_image": "https://www.gstatic.com/webp/gallery3/1.sm.png","product_price": 19.99},{"product_id": 2,"product_name": "Product 2","product_image": "https://www.gstatic.com/webp/gallery3/2.sm.png","product_price": 24.99},{"product_id": 3,"product_name": "Product 3","product_image": "https://www.gstatic.com/webp/gallery3/3.sm.png","product_price": 29.99}]';
        const data = JSON.parse(jsonArray);
    
        const cardElements = document.getElementsByClassName("card");
    
        for (var i = 0; i < cardElements.length; i++) {
            const currentCardElement = cardElements[i];
    
            const cardTitle = currentCardElement.querySelector(".title");
            cardTitle.textContent = data[i].product_name;
    
            const cardImage = currentCardElement.querySelector(".image");
            cardImage.src = data[i].product_image;
    
            const cardPrice = currentCardElement.querySelector(".price");
            cardPrice.textContent = `$${data[i].product_price.toFixed(2)}`;
        }
    </script>
    

    Here’s what was changed and why:

    1. querySelector is used instead of getElementsByClassName and item(0) since it’s more direct and cleaner to read when you’re only grabbing the first item.
    2. textContent is used instead of innerHTML when setting the text of an element. This is a good practice to avoid unexpected HTML rendering and potential cross-site scripting (XSS) vulnerabilities.
    3. For the image, src attribute is assigned the URL from data[i].product_image.
    4. The price is formatted to a string with two decimal places and a dollar sign is added for presentation.

    Now each card should display the correct image from the data you’ve provided. Make sure the number of .card elements matches the number of items in your data array to avoid errors.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search