0

Trying to print my htmlString in the .listing div but I'm only getting the last item in the array, yet the console.log loops correctly. what gives?

$.each(json.products, function(index, product) { 

        // build product block
    var htmlString = '<div class="product large-3 columns">';
    //open imgwrap
    htmlString += '<div class="imgwrap">';
    //get img src
    htmlString += ' <img class="item_img" src="http://api.example.com/assets/images/' + product.itemCode + '@2x.jpg" />';
    // close imgwrap
    htmlString += '</div>';
    // open textwrap
    htmlString += '<div class="textwrap">';
    // get productName
    htmlString += '<h1 class="product_headline">' + product.productName + '</h1>' ;
    // get itemCode
    htmlString += '<h4 class="item_id" >' + product.itemCode + '</h4>';
    // get description
    // get price
    // close divs
    htmlString += '</div>';

    console.log(htmlString);
    $('.listing').html(htmlString);

}); //end each

2 Answers 2

2

You are overriding the contents of listing in each iteration, instead you need to append the contents.

When you use .html() it will remove the current contents of the element, then replace it with the passed content. To add the new content after the existing one you can use .append()

If you want to clear the listing element, you can do it before the beginning of the loop as shown below

$('.listing').html(''); //clear the listing element if needed
$.each(json.products, function(index, product) {

  // build product block
  var htmlString = '<div class="product large-3 columns">';
  //open imgwrap
  htmlString += '<div class="imgwrap">';
  //get img src
  htmlString += ' <img class="item_img" src="http://api.example.com/assets/images/' + product.itemCode + '@2x.jpg" />';
  // close imgwrap
  htmlString += '</div>';
  // open textwrap
  htmlString += '<div class="textwrap">';
  // get productName
  htmlString += '<h1 class="product_headline">' + product.productName + '</h1>';
  // get itemCode
  htmlString += '<h4 class="item_id" >' + product.itemCode + '</h4>';
  // get description
  // get price
  // close divs
  htmlString += '</div>';

  console.log(htmlString);
  $('.listing').append(htmlString); //add the current content to existing one
}); //end each

Sign up to request clarification or add additional context in comments.

Comments

0

With .html() you're replacing the contents after each loop. Instead, append:

$('.listing').html(htmlString);

becomes:

$('.listing').append( $(htmlString) );

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.