Jack Marchetti
Jack Marchetti

Reputation: 15754

How do I use the jQuery $.each method to output proper HTML?

HTML:

<div id="twitter" style="float:left;">
    <span></span>
</div>

jQuery:

var obj = JSON.parse(data);

$.each(obj.items, function(i, item) {
  $("span", this).html("('<p>" + item.title + "</p>')").appendTo("#twitter");
  if (i == 5) return false;
});

I'm obviously doing something wrong, and can't seem to figure this out. I know the $.each method works, as I'm able to put alert(item.title) and get the expected result.

Basically all I want to do is, loop through the item and output:

<p> title </p>
<p> title 2 </p>

I just can't seem to figure this out

Upvotes: 3

Views: 760

Answers (2)

tvanfosson
tvanfosson

Reputation: 532455

   var obj = JSON.parse(data); 

    $.each(obj.items, function (i, item) { 
        $("<p>" + item.title + "</p>").appendTo("#twitter > span"); 
        if (i == 5) return false; 
    });

Upvotes: 5

Sampson
Sampson

Reputation: 268344

Without knowing what your JSON looks like, it's difficult to say what you ought to be doing:

$(obj.items).each(function(i,o){
  $("<p>").text(o.title).appendTo("#twitter > span");
  if (i == 5) return false;
});

Or possibly even:

for (var i = 1; i <= 5; i++) {
  $("<p>").text(o[i].title).appendTo("#twitter > span");
}

In reality, it's a little odd to be putting paragraphs within span tags.

Upvotes: 1

Related Questions