Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
3
rated 0 times [  6] [ 3]  / answers: 1 / hits: 24198  / 12 Years ago, tue, october 16, 2012, 12:00:00

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>

More From » jquery

 Answers
13

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.


[#82516] Monday, October 15, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
brodyfrancisi

Total Points: 1
Total Questions: 102
Total Answers: 89

Location: Marshall Islands
Member since Mon, May 31, 2021
3 Years ago
brodyfrancisi questions
;