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?

4
  • 1
    first of all "<p>" + value + "</p" to "<p>" + value + "</p>" Commented Jan 17, 2014 at 16:41
  • this should be marked as duplicate.... Commented Jan 17, 2014 at 16:43
  • @pilot - then hit close and mark it as duplicate so we can see the duplicate ? Commented Jan 17, 2014 at 16:56
  • @adeneo..question is about ? in function( ? ) . Here is How to loop through array in jquery Commented Jan 17, 2014 at 17:00

3 Answers 3

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>");
  });
});
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

0
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>');

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.