Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding letters from a string array into each dynamic div

I am trying to add each letter of a word to dynamically generated divs .box and .boxIn but the code is just adding the last word to each box! How can I fix this, and why is his happening? And is there any way to merge two loops into one loop?

Here is the demo

And this is the code which 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');
}
like image 934
Mona Coder Avatar asked Apr 24 '26 18:04

Mona Coder


1 Answers

That's because you are overriding html content of all the .boxIn elements, you should use the current iterator's index for selecting the target element:

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

http://jsfiddle.net/k4spypqj/

That being said there is no need to use 2 loops. You can set the generated element's content in the first loop using either text or html method.

like image 66
undefined Avatar answered Apr 27 '26 09:04

undefined



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!