2

I have something like this:

$(document).ready(function(){ 
  var veeCountries = ["America", "Japan"];

  $.each(veeCountries, function( ? ) {
    $("#content").html("<p>" + value + "</p>");
  });
});

I'm trying to output something like this:

<p>America</p>
<p>Japan</p>

But I'm stuck, what's the best and easiest way of doing this?

alexchenco
  • 53,565
  • 76
  • 241
  • 413

3 Answers3

4

Almost literally the same as the example in the docs on $.each(): http://api.jquery.com/jquery.each/

$.each(veeCountries, function(index, value) {
   $("#content").append("<p>" + value + "</p>");
  });
});
veddermatic
  • 1,082
  • 7
  • 15
3

The each method passes the index and the actual item of the array to the callback function.

$(document).ready(function(){ 
  var veeCountries = ["America", "Japan"];

  $.each(veeCountries, function(index, item) {
    $("#content").append("<p>" + item + "</p");
  });
});

Read the docs at jQuery.each

Saravana
  • 37,852
  • 18
  • 100
  • 108
2

The arguments for .each() if the index and the native DOM element, but using html() you're overwriting the content on each iteration.
Use append() inside the loop, or create the string in the loop and pass it to html() once.

$(document).ready(function(){ 
  var veeCountries = ["America", "Japan"],
      output       = '';

  $.each(veeCountries, function( index, value ) {
      output += "<p>" + value + "</p>");
  });

  $("#content").html(output);

});

or a little neater

$("#content").html('<p>' + veeCountries.join('</p><p>') + '</p>');
adeneo
  • 312,895
  • 29
  • 395
  • 388