Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create jQuery object from array of jQuery objects?

Tags:

arrays

jquery

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?

like image 269
zerkms Avatar asked Jul 03 '12 03:07

zerkms


People also ask

How do you create an array of arrays in jQuery?

$(document). ready(function() { var row = 4; var items = []; var total = []; $('#test tr:eq(' + row + ') td'). each(function(colindex, col) { //alert(colindex); t = $(this). contents(); items.

How do you iterate through an array in jQuery?

The $.each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time.

How do you object in jQuery?

Another way to make objects in Javascript using JQuery , getting data from the dom and pass it to the object Box and, for example, store them in an array of Boxes, could be: var box = {}; // my object var boxes = []; // my array $('div. test'). each(function (index, value) { color = $('p', this).

What is .each in jQuery?

each() jQuery's each() function is used to loop through each element of the target jQuery object — an object that contains one or more DOM elements, and exposes all jQuery functions. It's very useful for multi-element DOM manipulation, as well as iterating over arbitrary arrays and object properties.


2 Answers

Try

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

Or

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

The demo.

like image 62
xdazz Avatar answered Sep 28 '22 03:09

xdazz


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.

like image 27
Julian Avatar answered Sep 28 '22 05:09

Julian