Why can I add objects using appendTo but not add to jQuery?

How it 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 isn't it?

 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 method gives the following error:

This interface is not supported.

+1


a source to share


2 answers


I believe this is implementation related. If you look at the way AppendTo is written, it essentially takes every item in the items array and runs $ ("ul"). Append (items [i]).

Adds though doesn't seem to work for arrays. You will notice that even without a blank, your line will still not work. I don't quite understand how append works, but I believe the chomps function happens through all the arguments sequentially, but never tries to pop the elements out of the array. So what happens is that it tries to add an array to the element and fails. Ironically, this will work: $ ("ul"). Empty (). Append (items [0], items [1], items [2], items [3]);



Either way, you would need to do something like this to accomplish what you seem to be trying to do:

...

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

+1


a source


What if you change the second example of the last line to this



 $('ul').empty().append(items);

      

0


a source







All Articles