views:

146

answers:

1

The main jQuery method takes a second optional argument to provide context for the search. eg

$(".setA", ancestorOfSetsA);

However, the jQuery add() method does not accept this context argument. What I am trying to accomplish is:

$(".setA", ancestorOfSetsA).add(".setB", ancestorOfSetsB);

I am attempting this through a plugin that will overload the add() method but I can't figure out how to combine two jQuery objects into one jQuery object.

I would like to find a way to do a scoped add() with jQuery, but failing that, I'll write one myself if I can find a way to merge to jQuery objects.

+2  A: 

You can pass a jQuery collection into add just as well as a selector string:

$(".setA", ancestorOfSetsA).add( $(".setB", ancestorOfSetsB) );

If you want to overload add then you'll need to be careful to support the all of its behaviour. Someone (a plugin you might be using) might do this:

$( selector ).add('<div>new element</div>').appendTo( somethere );

Updated:

Here is the current add function from jQuery modified to take a context parameter:

jQuery.fn.add = function( selector, context ) {
    return this.pushStack( jQuery.unique( jQuery.merge(
     this.get(),
     typeof selector == 'string' ?
      jQuery( selector, context ) :
      jQuery.makeArray( selector )
    )));
}
Borgar
Based on your comments, here's what I came up with: $.fn._add = $.fn.add; $.fn.add = function(selector, context){ return this._add(context? $(selector, context): selector ); };Thoughts?
Jason Karns
That should work fine too. :-)
Borgar
I've modified my plugin to not pollute the $.fn namespace: var add = $.fn.add;$.fn.add = function(selector, context){ return add.call(this, $(selector, context));};I like this method as it won't need updated if jQuery.add() changes.
Jason Karns