jQuery addClass() to element generated after append()

t.y.append('<div></div>').addClass('lol'+i);

should be

t.y.append('<div></div>').find('div').addClass('lol'+i);

In the first case you are adding class to the div to which you are appending .. SO the context is still the parent div and not the newly appended div..

You need to find it first inside the parent and then add the class..

EDIT

If you want to just add the class to the last appended element ... Find the last div in the parent and then add the class to it.. This will make sure you are not adding the class to all the div's every single time you iterate in the loop..

t.y.append('<div></div>').find('div:last').addClass('lol'+i);

var t = this;

$(this.x).each(function(i, obj) {
    //append new div and add class too <div></div>
    var d = $('<div />').addClass('lol' + i);
    t.y.append(d);
});

When you append an element through .append, it doesn't change the context of the jQuery object.

You could write it like this:

$('<div></div>').appendTo(t.y).addClass('lol'+i);

or

$('<div></div>').addClass('lol'+i).appendTo(t.y);

(these both do the same thing, simply in different orders, the second possibly being more clear)

the context of the jQuery object will be the newly created div.


Try this:

t.y.append($('<div></div>').addClass('lol'+i));

Fiddle: http://jsfiddle.net/gromer/QkTdq/