1

I have a json file with an items category that lists items that are currently listed via an array. This item list is updated every few hours.

ex:

{
"items": [
    {
     "name": "Blueberry",
     "img": "website.com/blueberry.png"
    },
    {
     "name": "Raspberry",
     "img": "website.com/raspberry.png"
    }
         ]
}

Each item in the array is given an image and description. What I want to do is for every item, create an <img src='(item image url)'> element for the image that is listed inside the item, and create a <p> element for every item for the description that is listed.

Barmar
  • 741,623
  • 53
  • 500
  • 612
docyoda
  • 121
  • 8

2 Answers2

2

You can achieve this with JQuery with a for loop, and create the elements dynamically using the JQuery function $(...) (Tutorial here)

In the end, You'll probably end up with something like this:

// fetch the items from the url
$.getJSON("your url").then(function(response){

  //cycle through all the items in the array
  for(var i = 0; i < response.items.length; i++){

    // create image
    var image = $('<img>').attr("src", response.items[i].img);
    // make sure to set the attribute using the "attr" function 
    //  to avoid Cross Site Scripting (see the link below)

    // create text element
    var text = $('<p>').text(response.items[i].name);

    // append the items to the container
    $("container element").append(image).append(text);
   }
});

About Cross Site Scripting

maxpelic
  • 161
  • 11
0

To dinamically create elements in Pure JavaScript you can use the document.createElement


var imagesContainer = document.createElement('div')

for(var i = 0; i < array.length; i++){

    var img = document.createElement('img'),
        p = document.createElement('p');

    img.setAttribute("src", array[i].img);

    p.appendChild(document.createTextNode(array[i].name));

    imagesContainer.appendChild(img);
    imagesContainer.appendChild(p);
}

i think is this you are looking for :)

Mateus Martins
  • 442
  • 3
  • 16