Reputation: 21304
I have an array of arrays with values that I need to append to <div>
, but somehow .each()
function of underscore.js doesn't work as expected..
array: var arr = [['20-12-2012', 'Text'],['01-02-2012', 'Text2'], ...];
how my function looks:
_(arr).each(function (row, i) {
$('<div class="wrap"></div>').appendTo('#mainWrap');
_(row).each(function (line) {
$('<span>' + line + '</span>').appendTo('.wrap');
});
});
but result is that both two first arrays inside main array are applied to first .wrap
:
result:
<div id="mainWrap">
<div class="wrap">
<span>20-12-2012</span><span>Text</span>
<span>01-02-2012</span><span>Text2</span>
</div>
<div class="wrap">
<span>01-02-2012</span><span>Text2</span>
</div>
</div>
but I expect it to be as:
<div id="mainWrap">
<div class="wrap">
<span>20-12-2012</span><span>Text</span>
</div>
<div class="wrap">
<span>01-02-2012</span><span>Text2</span>
</div>
</div>
Upvotes: 0
Views: 211
Reputation: 123739
You need to select which .wrap
you need to append to. .wrap
will select all the element with class wrap
that has already been appended and it appends the span to all of them hence you see this behavior.
Try:
_(arr).each(function (row, i) {
var $wrap = $('<div class="wrap"></div>').appendTo('#mainWrap'); //save the wrap here
_(row).each(function (line) {
$('<span>' + line + '</span>').appendTo($wrap); //append to the wrap that was created in the previous loop.
});
});
If you have too many items to be appended consider appending to DOM element in the end rather than in the loop, save them to a temp jquery object and in the end append to the main element, more like this.
var arr = [['20-12-2012', 'Text'],['01-02-2012', 'Text2']], $main = $('<div/>');
_(arr).each(function (row, i) {
var $wrap = $('<div class="wrap"></div>').appendTo($main);
_(row).each(function (line) {
$('<span>' + line + '</span>').appendTo($wrap);
});
});
$('#mainWrap').append($main.html()); //Append to DOM now. For replace use .html
Upvotes: 2