views:

33

answers:

1

I'm authoring a plugin, and the plugin needs to do something like aggregate a set of jQuery objects. How does one do this?

For example:

<p><a>...</a></p>
<p><a>...</a></p>

With

(function( $ )
{
    $.fn.myfunc = function( settings )
    {

    };
})(jQuery);

Within the context of the plugin invoked with $('p').myfunc(), how would I return all the elements, for example? The elements I'm returning will not necessarily be contained or near the elements selected, as this is just an example.

+1  A: 

jQuery also accepts an array, so you can build your own node stack and create a jQuery object out of it.

Example:

(function( $ )
{
    $.fn.myfunc = function( settings )
    {
        var stack = [];
        stack.concat(this.find('a').toArray());
        stack.concat($('a.hot-links').toArray());
        return $($.unique(stack));
    };
})(jQuery);

Or simply:

return this.find('a'); // as return result of plugin

Also, look at .pushStack(), which lets you add elements to an already existing jQuery object.

BGerrissen
Exactly what I needed.
Stefan Kendall
A slight point of clarification, `.pushStack()` doesn't add any elements to the jQuery object, it returns a *new* jQuery object with the combination of the elements, the old/original object still has the same elements.
Nick Craver
@nick, good catch, basically you might as well work with arrays and create a new jQuery object out of it when you're done. Though not needed when doing minute concatenations.
BGerrissen