35

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?

hippietrail
17.3k21 gold badges114 silver badges181 bronze badges
asked Jul 3, 2012 at 3:44
2
  • 2
    Your fiddle seems to have an error; there is no element #c. Edit: in regards to your question I believe add() may be the only option. But I'm not entirely sure. Commented Jul 3, 2012 at 3:48
  • @powerbuoy: yep, that was a typo, thanks Commented Jul 3, 2012 at 3:50

7 Answers 7

28

Try

var d = $($.map(c, function(el){return $.makeArray(el)}));

Or

var d = $($.map(c, function(el){return el.get();}));

The demo.

answered Jul 3, 2012 at 4:01
Sign up to request clarification or add additional context in comments.

4 Comments

Yep, what I thought of is var d = $(c.map(function(el){ return el[0]; }));. +1 because currently it is the only answer that answers the original question
return el[0]; will only get the first element, if your selector matches multiple elements, the left element wont be in d.
right, didn't take it into account (most likely because I have only one element per object)
This seems super complicated. also I don't get it - why would you do $.makeArray(el) ?
21

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.

answered Dec 4, 2016 at 0:48

1 Comment

This seems way cleaner than the accepted answer to me.
1

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();
answered Jul 3, 2012 at 3:54

3 Comments

I already have an array of objects. So a,b,c variables from the example cannot be changed
Then probably you can create another array d by iterating through c!
Yep. Now it does the work. Though creating jquery object and using .add() could be a bit better
1

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();
answered Jul 3, 2012 at 4:14

Comments

0

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.

answered Jul 3, 2012 at 3:59

7 Comments

Yep, I can traverse them and what's next? This answer is not complete, as long as it doesn't say how exactly we get the jquery object as a result
@zerkms why do you need the jQuery object in particular as opposed to doing operations in the iteration?
because I need to pass the object in a next function, that assumes it is the single jquery object
@zerkms what is the function and why can't you pass them individually?
omg, that function is a "bit" more difficult than just hide(). You know of encapsulation? Well, some logic is encapsulated there, and I need to pass a jquery object because of a function interface.
|
0
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
}())
answered Jul 3, 2012 at 3:51

1 Comment

I don't have selectors, I have an array of objects
0

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>

answered Aug 19, 2024 at 19:39

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.