Turn array of jQuery elements into jQuery wrapped set of elements

前端 未结 11 1050
长发绾君心
长发绾君心 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:03

    To add single element:

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

    to convert array to jQuery set of elements:

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

    to add array of elements to existing elements:

    var $previousElements = $(),
         myjQueryElementArray = [$element1, $element2, $elementN];
    
    $previousElements.add($(myjQueryElementArray).map (function () {return this.toArray(); } ));
    
    0 讨论(0)
  • 2021-02-01 13:05

    Edit: I thought jQuery supported all Array methods, but nay, so here's a working version of my initial solution, albeit it's a bit odd since I am sticking to the same methods:

    var set; // The array of jQuery objects, 
             // but make sure it's an Array.
    var output = set.pop();
    $.each(set, function (_, item) { 
        return [].push.call(output, [].pop.call(item));
    });
    
    0 讨论(0)
  • 2021-02-01 13:05

    you could 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 am curious what brings you to this situation having an array of different jQuery elements. You know that you can select different elements using a comma? like $("li, ul > li:eq(0), div")

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

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

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

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

    jsFiddle.

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

    A bit more concise than the accepted answer, one can use the $.fn.toArray as the argument passed to $.fn.map:

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

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

    $.fn.map.call(list, $.fn.toArray);
    
    0 讨论(0)
  • 2021-02-01 13:14
    $('li').each(function(){
        $(this).doSomething();
    

    })

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