Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript AJAX Basics (retiring) AJAX and APIs Displaying the Photos

Bruno Dias
Bruno Dias
10,554 Points

How to to write the loop using JavaScript?

How can I write the loop using plain JavaScript?

I am not sure what I am missing here:

for (i = 0; i < photo.length; i++) {
      photoHTML += '<li class="grid-25 tablet-grid-50">';
      photoHTML += '<a href="' + photo.link + '" class="image" target="_blank">';
      photoHTML += '<img src="' + photo.media.m +'"></a></li>';
}

3 Answers

Simon Coates
Simon Coates
28,694 Points

Something like the following, but without the photos variable i added to simplify things.

var photos = [
{
link: "a.html"
}, {
link: "b.html"
}
];

photoHTML = "";
for (i = 0; i < photos.length; i++) {
    var photo = photos[i];

      photoHTML += '<a href="' + photo.link + '" class="image" target="_blank">';
}
console.log(photoHTML);
gaetano amoroso
gaetano amoroso
2,993 Points

from code I don't see many stuff: the loop is well done but maybe the problem is within the code that isn't visible in the post. I have tried to figure what you want really do.

photoHTML="<ul>";
 for (i = 0; i < photo.length; i++) {
      photoHTML += '<li class="grid-25 tablet-grid-50">';
      photoHTML += '<a href="' + photo.link + '" class="image" target="_blank">';
      photoHTML += '<img src="' + photo.media.m +'"></a></li>';
  }
photoHTML+="</ul>";

I hope that I have helped you

Jeremy Castanza
Jeremy Castanza
12,081 Points

We'd need to see more of your code. Based on what you published, I suspect that it has to do with the photos variable not being populated with the JSON object. With the way that the jQuery each function is setup, this is automatic. I suspect that your program doesn't know that "photo" is an item in the API's "items" array.