0

I have an array of 40 different image URLs being returned from an AJAX request. I'm trying to create a new HTML image element for each URL in the array using a For loop, as seen in the below code. For some reason, it's only displaying the image at the first URL and that's it. Any idea why the other 39 aren't showing up?

$(document).ready(function() {
  $.ajax({
    type: 'GET',
    dataType: 'json',
    url: 'https://****/images',
    success: function(data) {
      console.log(data);
      let container = document.getElementById('feed');
      let image = document.createElement("img");
      for (let i = 0; i < data.length; i++) {
        image.setAttribute('src', data[i]);
        container.appendChild(image);
      }
    }
  });
});


<body>

  <div id="feed">
  </div>

</body>

2 Answers 2

1

Try to create the element inside the loop.

  for (let i = 0; i < data.length; i++) {
     let image = document.createElement("img");
     image.setAttribute('src', data[i]);
     container.appendChild(image);
  }
Sign up to request clarification or add additional context in comments.

Comments

1

The way to create images is with new Image() and when appending multiple nodes to the DOM at once, it's better to first append the image nodes into a document fragment, and only when all the images have been appended to the fragment, then append the fragment itself into the Document (prevents redundant repaints)

// dummy data
const data = ['http://placekitten.com/100/100',
              'http://placekitten.com/100/150',
              'http://placekitten.com/100/180',
              'http://placekitten.com/100/200']

// create a dumpster-node for the images to reside in 
const fragment = document.createDocumentFragment();
 
// iterate the data and create <img> elements
data.forEach(url => {
     let image = new Image()
     image.src = url;
     fragment.appendChild(image);
})

// dump the fragment into the DOM all the once (FTW)
document.body.appendChild(fragment);

I've used Array forEach iterator in my example, because it's easier in my opinion, but you can use a for loop (or for..of loop)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.