Maverick
Maverick

Reputation: 2016

Append array item to DOM element with corresponding index (jQuery)

Lets say I have three divs in my HTML

<div>
    <h2>This is div 1</h2>
</div>
<div>
    <h2>This is div 2</h2>
</div>
<div>
    <h2>This is div 3</h2>
</div>

Also, I have a JavaScript array made of three nested arrays:

var array = [ 
    [ "<p>Bla bla</p>", "<p>Other stuff</p>"], 
    [ "<p>Another paragraph</p>"], 
    [ "<p>Yet another</p>", "<p>yes</p>", "<p>yes</p>" ] 
    ];

I am sure that this array will always have three members, just like the number of divs.

What I want to do is append the content of each of the nested arrays of the main array to the div with the corresponding number.

Something like:

for ( var i = 0; i < array.length; i++ ) {
    $('div').eq( i ).append( array[i] );
}

The above code doesn't work but I think my intention is clear.

You can find a working example here => http://jsfiddle.net/G8BsK/

Thanks.

Upvotes: 1

Views: 1327

Answers (3)

broox9
broox9

Reputation: 65

it's because the array values being appended are arrays themselves, not the html strings. You have to join them.

    for ( var i = 0; i < array.length; i++ ) {
        $('div').eq( i ).append( array[i].join('') );
    }

will work. the only difference is the 'array[i].join('')

Upvotes: 0

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76870

You should do

var array = [
    ["<p>Bla bla</p>", "<p>Other stuff</p>"],
    ["<p>Another paragraph</p>"],
    ["<p>Yet another</p>", "<p>yes</p>", "<p>yes</p>"]
    ];

for (var i = 0; i < array.length; i++) {
    var arr = array[i];
    for (var m = 0; m < arr.length; m++) {
        $('div').eq(i).append(arr[m]);
    };
}

http://jsfiddle.net/G8BsK/2/

Upvotes: 0

user1106925
user1106925

Reputation:

Change this...

.append( array[i] );

to this...

.append( array[i].join('') );

Although I would highly recommend taking the DOM selection out of the loop, and caching it.

var divs = $('div');
for ( var i = 0; i < array.length; i++ ) {
    divs.eq( i ).append( array[i].join('') );
}

...or just do this...

$('div').append(function(i) {
    return array[i].join('');
});

Upvotes: 5

Related Questions