Turn array of jQuery elements into jQuery wrapped set of elements

前端 未结 11 1051
长发绾君心
长发绾君心 2021-02-01 12:39

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

相关标签:
11条回答
  • 2021-02-01 13:17

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

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

    How do you apply to this question?

    If you have a list of elements 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())}, [])); snippet we use the array of elements and apply reduce reduce has 4 parameters but we can use the first two that are accumulator as 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 return array is wrapped into a jQuery object $(). You can replace elements with $('form#details :input') also.

    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 讨论(0)
  • 2021-02-01 13:21

    Say you have an array of jQuery elements:

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

    You can simply use the jQuery function ($()) directly on the array which will return a jQuery set:

    let jQuerySetOfElements = $(elementList);
    
    0 讨论(0)
  • 2021-02-01 13:22

    If what you really mean is how to convert:

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

    into the 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 a combined jQuery object that is the combination of the previous a, b and c jQuery objects in the array.

    I couldn't find any way to do it without the each() loop. The add() function accepts an array of DOM elements as an argument, but (at least according to the documentation), not an array of jQuery objects.


    Or, you could convert each jQuery object to a DOM element, which would likely be a little more efficient because it only makes one new jQuery object at the end:

    $([$(".a"), $(".b"), $(".c")].map(function(o) { return o.get() }));
    
    0 讨论(0)
  • 2021-02-01 13:23

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

    // 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 doesn't support adding a jQuery object, so you would need to use items.add(this.get()); instead.)

    0 讨论(0)
  • 2021-02-01 13:25

    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.

    0 讨论(0)
提交回复
热议问题