Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turn array of jQuery elements into jQuery wrapped set of elements

Tags:

jquery

Is there any elegant way of turning [$(div), $(span), $(li)] into $(div, span, li)?

What I need is a jQuery-wrapped set of elements instead of an array of jQuery elements. I would like to do this in as few lines of code as possible, and with minimal (if any) looping.

Edit: For those of you confused by this question, this code is copied and pasted from firebug using console.log on an array of elements that have already been selected.

like image 975
Scott Greenfield Avatar asked Jul 28 '11 23:07

Scott Greenfield


People also ask

How do I iterate an array of objects in jQuery?

each(), which is used to iterate, exclusively, over a jQuery object. 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.

What is $$ in jQuery?

$ is another, which is just an alias to jQuery . $$ is not provided by jQuery. It's provided by other libraries, such as Mootools or Prototype. js. More importantly, $$ is also provided in the console of modern browsers as an alias to document.

Does jQuery selector return array?

The jQuery selector code returns an array by itself. No need to do anything with it.

How do I create an array in jQuery?

Syntax And Declaration:var arr1=[]; var arr2=[1,2,3]; var arr2=["India","usa","uk"]; Type of Array: The type of an array is “object“. Iteration Approach: We use the length property of the array to iterate in the array.


1 Answers

jQuery's map() function is perfect for reshaping arrays and/or jQuery collections.

So, given an array set like so:

var arrayOfJQ_Objects = [$("div"), $("span"), $("li")]; 


This one line of code is all you need (See it in action at jsFiddle):

$(arrayOfJQ_Objects).map (function () {return this.toArray(); } ); 

Resulting in this console display in Firebug:

jQuery(div, span, li) 


Reference, also, jQuery's .toArray() function.

like image 129
Brock Adams Avatar answered Sep 21 '22 23:09

Brock Adams