Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery addClass() to element generated after append()

I am trying to add a class to a newly appended DIV without using something like:

t.y.append('<div class="lol'+i+'"></div>');

Here's a better example of what I'm trying to do:

var t = this;

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

Page load HTML looks like:

<div class=".slideButton0 .slideButton1 .slideButton2" id="sliderNav">
    <div></div>
    <div></div>
    <div></div>
</div>
like image 462
Dan Kanze Avatar asked Oct 16 '12 21:10

Dan Kanze


2 Answers

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.

like image 143
Shmiddty Avatar answered Oct 04 '22 07:10

Shmiddty


Try this:

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

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

like image 44
Gromer Avatar answered Oct 04 '22 05:10

Gromer