tags:

views:

148

answers:

2

How come this works:

 var items = [];
 $.each([1,2,3,4], function() {
     items.push($('<li />').html('test' + this));
 });
 // clearing/appending as two seperate calls
 $('ul').empty();
 $(items).appendTo('ul');

but this doesn't?

 var items = [];
 $.each([1,2,3,4], function() {
     items.push($('<li />').html('test' + this));
 });
 // clearing/appending in one fluent call
 $('ul').empty().append($(items));

This way throws the following error:

No such interface supported.

A: 

What if you change your 2nd example's last line to this

 $('ul').empty().append(items);
alex
+1  A: 

I believe it's due to implementation. If you look at the way AppendTo is written, it's essentially taking each item in the items array and running a $("ul").append(items[i]).

Append though doesn't seem to work on arrays. You'll notice that even without the empty, your line still won't work. I don't completely understand the workings of append, but I believe what happens is the function chomps through all the arguments sequentially, but never attempts to break the elements out of an array. So what happens is that it attempts to append an array to an element and fails. Ironically, this would work: $("ul").empty().append(items[0], items[1], items[2], items[3]);

Anyway you'd have to do something like this to accomplish what you seem to be aiming to do:

$("ul").empty(); $(items).each(function(e, elem) {$('ul').append(elem);})

jacobangel
Thanks, although I may just stick with the first example. The goal was to limit the number of times I had to select the ul element. the first example selects it twice, second is only once, but your example here is 1+n elements in the array.
bendewey