cusejuice
cusejuice

Reputation: 10681

jQuery: clone HTML with information from Object Literal

I have the following HTML that I want to repeat 5 times within a div container (.container).

<div class="block">
   <div class="name">Name</div>
   <div class="content>Content</div>
</div>

I have the following object literal:

var main_content = {
    "content_1": {
        "name": "Joe",
        "position": "Baker"
    },
    "content_2": {
        "name": "Jane",
        "position": "Waitress"
    }
     "content_3", etc
}

I want to clone the top HTML and for each block, change the name and content to its respective object literal item. So I want the output of the HTML to look like below. How can I do this?

<div class="block">
   <div class="name">Joe</div>
   <div class="position>Baker</div>
</div>
<div class="block">
   <div class="name">Jane</div>
   <div class="position>Waitress</div>
</div>
...

Upvotes: 1

Views: 117

Answers (2)

hereandnow78
hereandnow78

Reputation: 14434

dont append to the DOM in a loop:

var block, resultHtml = '';
for(block in main_content){
  resultHtml += '<div class="block"><div class="name">' + main_content[block].name + '</div><div class="position">' + main_content[block].position + '</div></div>'
}
$('your-selector').append(resultHtml); 

Upvotes: 1

BenM
BenM

Reputation: 53198

This should be relatively easy using jQuery. Will this work for you?

for(var i in main_content)
{
    var name = main_content[i].name,
    position = main_content[i].position,

    template = $('<div class="block">\
                      <div class="name">'+name+'</div>\
                      <div class="position">'+position+'</div>\
                  </div>');

    template.appendTo($('.container'));
}

Please see the working jsFiddle demo here > http://jsfiddle.net/jLPkS/

Upvotes: 1

Related Questions