Reputation: 254906
Let's say I have an array of jQuery objects and wish to have one compound jQuery object instead.
What would be the solution other than manual traversing an array and appending the elements to the just created jquery object using .add()
?
This doesn't do what I want:
var a = $('#a'),
b = $('#b'),
c = [a, b];
// the lines above is the set up, they cannot be changed
var d = $(c);
d.hide();
http://jsfiddle.net/zerkms/896eN/1/
The expected result is both divs are hidden.
Any ideas?
Upvotes: 35
Views: 16204
Reputation: 48600
Here is the most concise version for converting an array of jQuery objects into a single jQuery collection.
(function($) {
/**
* Converts an array of jQuery objects into a single jQuery collection.
*
* @param {jQuery[]} $elements - An array of jQuery objects.
* @returns {jQuery} A jQuery collection containing all the elements.
*/
$.fromArray = function($elements) {
return $($.map($elements, function($el) {
return $el.toArray();
}));
};
})(jQuery);
const $a = $('.a'), $b = $('.b'), $c = $('.c');
const $all = $.fromArray([$a, $b, $c]); // jQuery collection
// Iterate using jQuery built-ins
$all.each(function() {
console.log(this);
});
console.log($all.last().text()); // C
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div class="a">A</div>
<div class="b">B</div>
<div class="c">C</div>
Upvotes: 0
Reputation: 2634
I came here looking for a cleaner answer than I already had, but didn't find one. For the sake of the next guy to come along I guess I'll post my solution instead:
var a = $('#a'),
b = $('#b'),
c = [a, b];
var d = c.reduce($.merge);
d.hide();
I'm sort of surprised there isn't some jQuery
specific method that makes this cleaner, but Array.reduce
is definitely the correct tool for this job if nothing more specific exists in jQuery
.
Upvotes: 20
Reputation: 18078
Try this:
var a = $('#a'),
b = $('#b'),
c = [a, b],
d = $();
$.each(c, function(i, jqObj) {
$.merge(d, jqObj);
});
d.hide();
or:
var a = $('#a'),
b = $('#b'),
c = [a, b],
d = $();
$.each(c, function(i, jqObj) {
d = d.add(jqObj);
});
d.hide();
Upvotes: 1
Reputation: 388316
Can you try
var a = $('#a'),
b = $('#b'),
c = [a, b];
d = [];
$.each(c, function(i, v){
if(v.length>0){
d.push(v[0]);
}
});
e = $(d);
e.hide();
Upvotes: 1
Reputation: 160833
Try
var d = $($.map(c, function(el){return $.makeArray(el)}));
Or
var d = $($.map(c, function(el){return el.get();}));
Upvotes: 28
Reputation: 94101
var els = ['#a', '#b', '#c']
var $els = $(els.join(', '))
Edit: This will do, ugly tho:
var d = $(function(){
var els = []
for (var i = 0, l = c.length; i < l; i++)
els.push(c[i][0])
return els
}())
Upvotes: 0
Reputation: 191729
Assuming you know that you have an array of jQuery objects, you can use $.each
to cycle through them (or just treat them as a normal array to cycle through them). You can use this to create a combined selector if you like, or just do operations on them in the iterator.
Upvotes: 0