Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

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.

like image 802
Vilx- Avatar asked May 16 '13 09:05

Vilx-


People also ask

What is wrap function in jQuery?

jQuery wrap() Method The wrap() method wraps specified HTML element(s) around each selected element.

What does $() return in jQuery?

$() does not return the jQuery function, (which is $ itself,) but returns a wrapped set, with all those helpful methods on it.

What is wrap in js?

Wrapping JavaScript functions lets you add common logic to functions you do not control, like native and external functions. Many JavaScript libraries, like the TrackJS agents, need to wrap external functions to do their work.

Does jQuery always return an array?

The jQuery function always returns a jQuery object (that is based on an array), even if there are no elements that matches the selector.


Video Answer


1 Answers

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);
});
like image 69
Henrik Andersson Avatar answered Oct 21 '22 10:10

Henrik Andersson