Turn array of jQuery elements into jQuery wrapped set of elements
jQuery's map()
function is perfect for reshaping arrays and/or jQuery collections.
So, given an array set like so:
var arrayOfJQ_Objects = [$("div"), $("span"), $("li")];
This one line of code is all you need (See it in action at jsFiddle):
$(arrayOfJQ_Objects).map (function () {return this.toArray(); } );
Resulting in this console display in Firebug:
jQuery(div, span, li)
Reference, also, jQuery's .toArray()
function.
If what you really mean is how to convert:
[$(a), $(b), $(c)]
into the result of:
$(a, b, c)
then you can use the add function to add each jQuery object to another jQuery object:
var x = $(); // empty jQuery object
$.each([$(a), $(b), $(c)], function(i, o) {x = x.add(o)});
At this point, x will contain a combined jQuery object that is the combination of the previous a, b and c jQuery objects in the array.
I couldn't find any way to do it without the each()
loop. The add()
function accepts an array of DOM elements as an argument, but (at least according to the documentation), not an array of jQuery objects.
Or, you could convert each jQuery object to a DOM element, which would likely be a little more efficient because it only makes one new jQuery object at the end:
$([$(".a"), $(".b"), $(".c")].map(function(o) { return o.get() }));
A bit more concise than the accepted answer, one can use the $.fn.toArray
as the argument passed to $.fn.map
:
var list = [$('<a>'), $('<b>'), $('<i>')];
$(list).map($.fn.toArray);
Or perhaps (this is really inferior, but only has one function call in your code):
$.fn.map.call(list, $.fn.toArray);