Turn array of jQuery elements into jQuery wrapped set of elements

前端 未结 11 1073
长发绾君心
长发绾君心 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;
    }
    
    

提交回复
热议问题