Is there any elegant way of turning [$(div), $(span), $(li)]
into $(div, span, li)
?
What I need is a jQuery-wrapped set of elements instead of
To add single element:
var $previousElements = $();
$previousElements.add($element);
to convert array to jQuery set of elements:
var myjQueryElementArray = [$element1, $element2, $elementN];
$(myjQueryElementArray ).map (function () {return this.toArray(); } );
to add array of elements to existing elements:
var $previousElements = $(),
myjQueryElementArray = [$element1, $element2, $elementN];
$previousElements.add($(myjQueryElementArray).map (function () {return this.toArray(); } ));
Edit: I thought jQuery supported all Array
methods, but nay, so here's a working version of my initial solution, albeit it's a bit odd since I am sticking to the same methods:
var set; // The array of jQuery objects,
// but make sure it's an Array.
var output = set.pop();
$.each(set, function (_, item) {
return [].push.call(output, [].pop.call(item));
});
you could do something like this:
var $temp = $();
$.each([$("li"), $("li"), $("li")], function(){
$temp.push(this[0]);
})
$temp all your elements in one jQuery selector
But i am curious what brings you to this situation having an array of different jQuery elements. You know that you can select different elements using a comma? like $("li, ul > li:eq(0), div")
edit as Guffa pointed out, this only adds the first element of each section. .add()
is a better choice then .push()
here.
If Array.prototype.reduce()
is supported in your environment.
var jQueryCollection = [$("a"), $("div")]
.reduce(function (masterCollection, collection) {
return masterCollection.add(collection);
}, $());
jsFiddle.
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);
$('li').each(function(){
$(this).doSomething();
})