holyredbeard
holyredbeard

Reputation: 21188

Append data to divs dynamically

I'm creating eight divs which I want to be appended one and one to eight other divs, with the use of these divs classes:

var foo1 = "<span class='fooClass'>Foo text1</span>";
var foo2 = "<span class='fooClass'>Foo text2</span>";
var foo3 = "<span class='fooClass'>Foo text3</span>";
var foo4 = "<span class='fooClass'>Foo text4</span>";
var foo5 = "<span class='fooClass'>Foo text5</span>";
var foo6 = "<span class='fooClass'>Foo text6</span>";
var foo7 = "<span class='fooClass'>Foo text7</span>";
var foo8 = "<span class='fooClass'>Foo text8</span>";

$('.fooData').each(function(i) {
    $('this').append('foo' + i);
});

The .fooData divs (again, there are eight of them as well) is created before the divs that I want to append is created.

However this doesn't work (i.e no data is added to the .fooData-divs). What am I doing wrong?

Note: The .fooData-divs also have other classes if that matters, e.g:

<div class="color4 fooData leftSide"></div>

Upvotes: 2

Views: 1452

Answers (2)

crackmigg
crackmigg

Reputation: 5881

Nearly everything in this script is wrong. The index of the each starts with 0and you do not have a variable foo0 defined. Adding to this you append a string to the fooData Elements, not your defined variables. Also $('this')(again a string) will not work.

Upvotes: 0

Adil
Adil

Reputation: 148110

It would be better to use array instead of using variables and evaluating their names.

foo = [];
var foo[0] = $("<span class='fooClass'>Foo text1</span>");
var foo[1] = $("<span class='fooClass'>Foo text2</span>");

$('.fooData').each(function(i) {
    $(this).append(foo[i]);
});

Upvotes: 2

Related Questions