1

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.

3
  • Both examples work for me, Firefox: 3.0.10 jQuery:1.2.3, what exactly is throwing the error ? Commented May 21, 2009 at 23:05
  • the latter failed for me on Firefox 3.0.10 with jQuery 1.3, but the first worked. Commented May 21, 2009 at 23:56
  • I'm using jQuery 1.3 and IE 8 Commented May 22, 2009 at 11:59

2 Answers 2

1

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);})

Sign up to request clarification or add additional context in comments.

1 Comment

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.
0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.