Is there a way to do the 'scoped' add () in jQuery?
The main jQuery method accepts a second optional argument to provide the context for the search. eg,
$(".setA", ancestorOfSetsA);
However, the jQuery method add()
does not accept this context argument. I am trying to accomplish the following:
$(".setA", ancestorOfSetsA).add(".setB", ancestorOfSetsB);
I am trying this through a plugin that will overload a method add()
, but I cannot figure out how to combine two jQuery objects into one jQuery object.
I would like to find a way to do scoped add()
with jQuery, but otherwise I'll write myself if I find a way to merge with jQuery objects.
source to share
You can pass a jQuery collection in the add
same way as a selector string:
$(".setA", ancestorOfSetsA).add( $(".setB", ancestorOfSetsB) );
If you want to overload add
, you need to be careful to maintain all of its behavior. Someone (a plugin you could use) could do this:
$( selector ).add('<div>new element</div>').appendTo( somethere );
Updated:
Here is the current add function from jQuery modified to accept 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 )
)));
}
source to share