views:

152

answers:

2

I am looking to add functionality to a jQuery method.

I have the code

$('li.s').appendTo('#target');

There are multiple elements which match li.s, and I can see it's grabbed correctly using Firebug.

The append method works fine without my wrapper. However, with my wrapper (which shouldn't change anything about the function):

var oldAppend = $.fn.append;

$.fn.append = function(expr) {
    return oldAppend.call(this, expr);
};

The correct jQuery object is returned, but only the first li.s is appended to #target, instead of all of them. Why is this? Where am I losing my other elements in the call to oldAppend?

A: 

I haven't delved into the jQuery code to check this, but most functions should usually return this.each(fn):

$.fn.append = function(expr) {
    return this.each(function() {
        oldAppend.call($(this), expr);
    });
};

You'll notice I've had to wrap this in a jQuery object inside the inner function, as the append method expects that to be the context. I'm not sure, but you may find you need to wrap the outer reference to this as well:

return $(this).each
roryf
Still fails (same problem). I had tried this myself, and just re-did it to make sure I didn't mess up the first time.
strager
A: 

The problem is that you (I) are note passing all of the arguments sent to append by appendTo. Use apply and arguments like so:

var oldAppend = $.fn.append;

$.fn.append = function() {
    return oldAppend.apply(this, arguments);
};

(Remember that all functions have arguments, so you need to var args = arguments in the proper scope to access those arguments, e.g. when using $.each.)

strager