DN0300
DN0300

Reputation: 876

How to wrap for loop in a div?

I have been stuck on this silly thing, I can't figure out how to wrap my for loop inside of a div.

for (item = 0; item < event.length; item++) {
        var ID = event[item].id;
        element.find(".title").after("<span class='id'><img src='/avatar/" +ID+ "'/></span>");
        }

I want to achive this:

<div>
<span></span>
<span></span>
<span></span>
</div>

Any Help is much apprciated.

Upvotes: 0

Views: 212

Answers (2)

Harsh Makadia
Harsh Makadia

Reputation: 3443

$(document).ready(function() {  
//Assume sample event array 
var event = [1, 2, 3];
for (item = 0; item < event.length; item++) {
    var ID = event[item];
    $("<span class='id'><img src='/avatar/" +ID+ "'/></span<br>").appendTo('#name');
  };
});

Considering sample HTML Below

<div id="name">
   hello
</div>

This way you can populate content inside the div

Upvotes: 0

brk
brk

Reputation: 50291

Hope this snippet will be useful

// a variable for the dynamically created span
var spanString = "";
for (item = 0; item < event.length; item++) {
  var ID = event[item].id;
  // new string will con cat wit the spanString
  spanString += ("<span class='id'><img src='/avatar/" + ID + "'/></span>");
}

// append the spanString to the `div.title`
$(".title").append($(spanString))

Upvotes: 2

Related Questions