Rotate jQuery element array in jQuery wrapped in element set

Is there an elegant way to turn [$(div), $(span), $(li)] into $(div, span, li) ?

I need an element set consisting of jQuery, instead of an array of jQuery elements. I would like to do this as few lines of code as possible and with a minimal (if any) loop.

Edit: For those you confuse about this issue, this code is copied and pasted from firebug using console.log into an array of elements that are already selected .

+49
jquery
Jul 28 2018-11-23T00:
source share
11 answers

The jQuery map() function is ideal for rebuilding jQuery arrays and / or collections.

So, given the array given as follows:

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


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

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

The resulting display of this console in Firebug:

 jQuery(div, span, li) 


The link is also a jQuery .toArray() function .

+47
Jul 29 2018-11-11T00:
source share

If you really mean how to convert:

 [$(a), $(b), $(c)] 

as a result of:

 $(a, b, c) 

then you can use the add function to add each jQuery object to another jQuery object:

 var x = $(); // empty jQuery object $.each([$(a), $(b), $(c)], function(i, o) {x = x.add(o)}); 

At this point, x will contain the combined jQuery object, which is a combination of the previous jQuery objects a, b, and c in the array.

I could not find a way to do this without each() loop. The add() function takes an array of DOM elements as an argument, but (at least according to the documentation ), not an array of jQuery objects.




Or you can convert each jQuery object to a DOM element, which is likely to be a little more efficient, since in the end it creates only one new jQuery object:

 $([$(".a"), $(".b"), $(".c")].map(function(o) { return o.get() })); 
+17
Jul 29 2018-11-11T00:
source share

You can use the add method to copy elements to a jQuery object in another. This will copy all the elements from each of the jQuery objects in the source array to the jQuery items object:

 // Create an empty jQuery object var items = $([]); // Add the elements from each jQuery object to it $.each(source, function(){ items = items.add(this); }); 

(Prior to version 1.3.2, the add method does not support adding a jQuery object, so you will need to use items.add(this.get()); )

+5
Jul 29 '11 at 0:10
source share

A little shorter than the accepted answer, you can use $.fn.toArray as the argument passed to $.fn.map :

 var list = [$('<a>'), $('<b>'), $('<i>')]; $(list).map($.fn.toArray); 

Or maybe (this is really inferior, but has only one function call in your code):

 $.fn.map.call(list, $.fn.toArray); 
+5
Nov 08 '15 at 14:02
source share

Let's say you have an array of jQuery elements:

 let elementList = [$("selector1"), $("selector2"), $("selector3"), ...]; 

You can simply use the jQuery ( $() ) function directly in the array that will return the jQuery set:

 let jQuerySetOfElements = $(elementList); 
+2
Nov 18 '14 at 21:47
source share

Change I thought jQuery supports all Array methods, but no, so here is the working version of my original solution, although a bit strange, since I stick to the same methods:

 var set; // The array of jQuery objects, // but make sure it an Array. var output = set.pop(); $.each(set, function (_, item) { return [].push.call(output, [].pop.call(item)); }); 
+1
Jul 29 2018-11-11T00:
source share

To add a single item:

 var $previousElements = $(); $previousElements.add($element); 

to convert an array to a jQuery element set:

 var myjQueryElementArray = [$element1, $element2, $elementN]; $(myjQueryElementArray ).map (function () {return this.toArray(); } ); 

add an array of elements to existing elements:

 var $previousElements = $(), myjQueryElementArray = [$element1, $element2, $elementN]; $previousElements.add($(myjQueryElementArray).map (function () {return this.toArray(); } )); 
+1
Mar 15 '13 at 7:48
source share

If Array.prototype.reduce() supported in your environment.

 var jQueryCollection = [$("a"), $("div")] .reduce(function (masterCollection, collection) { return masterCollection.add(collection); }, $()); 

jsFiddle .

+1
Mar 30 '13 at 0:04
source share

you can do something like this:

 var $temp = $(); $.each([$("li"), $("li"), $("li")], function(){ $temp.push(this[0]); }) 

$ temp all your elements in one jQuery selector

But I'm curious what led you to this situation with an array of different jQuery elements. Do you know that you can select different elements using a comma? like $("li, ul > li:eq(0), div")

edit as Guff pointed out, this only adds the first element of each section. .add() is the best choice, then .push() here.

0
Jul 29 2018-11-11T00:
source share

I have had a similar problem for a long time. I have a huge form and I need to get every input . So my idea was to take each input as a jQuery object and turn it into a packaged set of jQuery elements. How can i do this? Well, this is the solution to your question.

  1. First you need to create an empty array as a jQuery object, for example: let fields = $([]); ,
  2. Now use the line containing the selector expression to get the elements you need in this example: 'form#details :input' as jQuery objects.
  3. Then use the .each method to extract the necessary information and add the jQuery object to the jQuery set packer: fields = fields.add(input);

How do you feel about this issue?

If you have a list of elements, then let elements = [$('#gw_id'), $('#erv_id'), $('#name')]; you can replace $('form#details :input') with elements ;

Another alternative is to use .reduce vanilla js. in this let set = $(elements.reduce((acc, cur) => {return acc.concat(cur.get())}, [])); the code fragment we use the elements array and apply reduce reduction has 4 parameters, but we can use the first two, which are accumulator in acc and currentValue as cur also we use the Arrow ( => ) function to reduce the callback. In this callback, we concatenate each current value in a new array. Finally, the returned array is placed in a jQuery $() object. You can also replace elements with $('form#details :input') .

 let fields = $([]); let elements = [$('#gw_id'), $('#erv_id'), $('#name')]; $(function() { console.log('List of fields: '); $('form#details :input').each((index, value) => { let input = $(value); let id = input.attr('id'); let type = input.attr('type'); fields = fields.add(input); if (id && type == 'text') { console.log('Input: ' + id + ' | Text: ' + type); } }); fields.addClass('ui-state-error'); let set = $(elements.reduce((acc, cur) => { return acc.concat(cur.get()) }, [])); console.log('Set list: '); set.each((index, value) => { let input = $(value); let id = input.attr('id'); let type = input.attr('type'); console.log('Input: ' + id + ' | Text: ' + type); }); }); 
 .ui-state-error { background: yellow; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form id="details"> <fieldset> <p> <label for="gw_id">GW Id</label> <input type="text" name="gw_id" id="gw_id" value="" class="text ui-widget-content ui-corner-all"> </p> <p> <label for="erv_id">ERV Id</label> <input type="text" name="erv_id" id="erv_id" value="" class="text ui-widget-content ui-corner-all"> </p> <p> <label for="name">Name</label> <input type="text" name="name" id="name" value="" class="text ui-widget-content ui-corner-all"> </p> <p> <label for="description">Description</label> <input type="text" name="description" id="description" value="" class="text ui-widget-content ui-corner-all"> </p> <input type="hidden" name="no" id="no" value="23" disabled readonly> <!-- Allow form submission with keyboard without duplicating the dialog button --> <input type="submit" tabindex="-1" style="position:absolute; top:-1000px"> </fieldset> </form> 
0
Feb 01 '19 at 4:26
source share
 $('li').each(function(){ $(this).doSomething(); 

})

-2
Jul 29 2018-11-11T00:
source share



All Articles