Problem adding letters from string array to each dynamic Div

I am trying to add every letter of a word to dynamically generated divs .box

and .boxIn

but the code just adds the last word to every window! please let me know how to fix this and WHY is this happening? and is there a way to combine two loops into one loop?

Here is a demo

and this is the code i have

var letters = [];
var str = "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
var letters = str.split(",");
var word = "Test App";
for (var i = 0; i < word.length; i++) {
    $('<div class="box"><div class="boxIn"></div></div>').appendTo(".wrapper");
}

for (var j = 0; j < word.length; j++) {
    $('.boxIn').html(word.charAt(j)).addClass('animated fadeInDown');
}

      

+3


source to share


3 answers


It's easy enough to combine them, which will make it more efficient and save you the html over the ride error you have

var letters = [];
var str = "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
var letters = str.split(",");
var word = "Test App";
for (var i = 0; i < word.length; i++) {
    $('<div class="box"><div class="boxIn animated fadeInDown">'+
              word.charAt(i)+'</div></div>').appendTo(".wrapper");
}

      



DEMO

+2


source


Which, since you are overriding the html content of all elements .boxIn

, you should use the current iterator index to select the target element:

$('.boxIn').eq(j).html(word.charAt(j)).addClass('animated fadeInDown');

      



http://jsfiddle.net/k4spypqj/

There is no need to use 2 cycles. You can set the content of the generated element in the first loop using the text

or method html

.

+4


source


The problem is how you set the html. You select all elements with class boxIn and set char at position j in html (from all elements). To set only char to one element, you can constrain the selection with a function .eq()

.

In your case, it would be:

for (var j = 0; j < word.length; j++) {
    $('.boxIn').eq(j).html(word.charAt(j)).addClass('animated fadeInDown');
}

      

If you want to combine the two loops, you can set the value directly in your html string: for (var i = 0; i <word.length; i ++) {$ ('' + word.charAt (i) + '') .appendTo (". wrapper"). children ('. boxIn'). addClass ('animated fadeInDown'); }

or if you add it separately:

for (var i = 0; i < word.length; i++) {
    $('<div class="box"><div class="boxIn"></div></div>').appendTo(".wrapper").children('.boxIn').addClass('animated fadeInDown').html(word.charAt(i));
}

      

jsfiddle

+1


source







All Articles