I am building my own JS library backed by jquery. The constructor starts building on top of an existing div to flesh it out. In the library I am making an ajax call, so to this initial div I know how to append like (where this is the initial div passed in):
var t = this;
var sdiv = t.append("<ul class='foo'></ul>");
So now I need to loop through and append elements to the variable "sdiv". For some reason
$(sdiv).append("<li class='bar'>" + element[i] + "</li>");
isn't working/rendering. How do you append elements to other elements created as variables?
Thanks
I am building my own JS library backed by jquery. The constructor starts building on top of an existing div to flesh it out. In the library I am making an ajax call, so to this initial div I know how to append like (where this is the initial div passed in):
var t = this;
var sdiv = t.append("<ul class='foo'></ul>");
So now I need to loop through and append elements to the variable "sdiv". For some reason
$(sdiv).append("<li class='bar'>" + element[i] + "</li>");
isn't working/rendering. How do you append elements to other elements created as variables?
Thanks
Share Improve this question edited Jun 19, 2014 at 21:06 MeanDean73 asked Jun 18, 2014 at 17:01 MeanDean73MeanDean73 1551 gold badge3 silver badges13 bronze badges 7-
What does the this in
var t = this
refer to? Could it be pointing to window? If not have you considered that it should bevar t = $(this)
? – PeterKA Commented Jun 18, 2014 at 17:04 - sorry that was a mistype on my part – MeanDean73 Commented Jun 18, 2014 at 17:06
- Correcting that should fix everything, right? Or is there an issue still outstanding? – PeterKA Commented Jun 18, 2014 at 17:07
- @user3558931 there are other issues. See my answer for how to fix them. – Rory McCrossan Commented Jun 18, 2014 at 17:11
- @RoryMcCrossan, great! I see what you mean. – PeterKA Commented Jun 18, 2014 at 17:15
2 Answers
Reset to default 2It's not working because sdiv
will be the same as the t
variable, as append
returns the originally selected element.
Instead, create the ul
in it's own variable, then use that reference when appending. Try this:
var $t = $(this);
var $sdiv = $('<ul />', { class: 'foo' }).appendTo($t);
// in your loop...
$('<li />', { class: 'bar', text: element[i] }).appendTo($sdiv);
Note that I also wrapped this
in a jQuery object. Assuming this code is being executed in an event handler, you would need to do that.
@RoryMcCrossan has provided a great answer. Another approach could be as follows:
var $t = $(this)
var $sdiv = $('<ul class="foo"/>');
Then in your loop do the following:
$sdiv.append( $('<ul class="bar"/>').text( element[i] ) );
Then finally append $sdiv
to $t
:
$t.append( $sdiv );