Vilx-
Vilx-

Reputation: 106970

Is there a quick way to wrap jQuery around every element in an array?

Can this be done in a more concise way?

var src = $('div');
var dest = [];

for ( var i = 0; i < src.length; i++)
    dest[i] = $(src[i]);

I can only think of this, which is still pretty verbose:

var dest = [];
$('div').each(function() { dest.push($(this)); });

Does jQuery offer anything better for this case? I can't find it.


To address some of the recurring questions in the comments:

src[i] is already a jQuery object, calling jQuery(src[i]) doesn't do anything.

No, it's a plain DOM node, without any jQuery wrappings at all.

Just out of curiosity, why do it at all?

Because afterwards I'll need to do quite a lot of mucking around with each element individually. For example, I need to go over all of them to find the tallest one, then set the rest of them to the same height. After that I need to get all their widths and perform some layouting based on that (so each element gets its x & y coordinates based on the widths of other elements). Etc.

All these manipulations are done more easily if I can use the shorthand functions provided by jQuery, but that means that I need to wrap each element individually ($('div') only returned a wrapper around all of them). And since I need to visit every element multiple times, I'd like to increase performance by wrapping each of them only once, not on every visit.

Upvotes: 8

Views: 1451

Answers (2)

Jashwant
Jashwant

Reputation: 29015

You should not re-convert dom node to jQuery object.

You should try something like this,

var src = $('div');
var dest = [];

for ( var i = 0, l = src.length; i < l; i++) {
    dest[i] = src.eq(i);
}

console.log(dest);

Or even better,

var src = document.getElementsByTagName('div');
var dest = [];
for ( var i = 0, l = src.length; i < l; i++) {
    dest[i] = $(src[i]);
}
console.log(dest);


I am not very good at js perf, but here's a test http://jsperf.com/eq-vs-vs-vanilla

Upvotes: 1

Henrik Andersson
Henrik Andersson

Reputation: 47202

This is exactly what the map() is for. You're looping over each element and apply a function to the element and push it onto a new Array.

var wrapped  = $.map($('div'), function(){ return $(this); });

or for readability

var wrapped  = $.map($('div'), function(val, i) {
    return $(val);
});

Upvotes: 8

Related Questions