1

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.

3 Answers 3

5

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('');
});
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, thanks, it works like this. I forgot to join them. :) Btw in my actual code I have the dom elements cached.
0

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/

Comments

0

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('')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.