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?
$(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.
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.
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).
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.
Try
var d = $($.map(c, function(el){return $.makeArray(el)}));
Or
var d = $($.map(c, function(el){return el.get();}));
The demo.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With