开发者

Merging jQuery objects

Is it possible to merge several jQuery DOM objects into one array and call jQuery methods on all of them?

F.ex:

<button>one</button>
<h3>two</h3&g开发者_开发技巧t;

<script>

var btn = $('button');
var h3 = $('h3');

$([btn,h3]).hide();

</script>

This doesn't work. I know I can use the 'button,h3' selector here but in some cases I already have several jQuery DOM elements and I need to merge them so I can call jQuery prototypes on all of them.

something like:

$.merge([btn,h3]).hide();

would work. Any ideas?

UPDATE:

Solved it. You can do it like this:

$.fn.add.call(btn,h3);

I'm going to accept the add() suggestion as for pointing me in the right direction.


.add() does exactly what you're after.

h3.add(btn).hide();

If you wanted to make it a little more convenient for yourself, with a "merge" function like in your question, this could be added easily:

$.merge = function(objs) {
    var ret = objs.shift();
    while (objs.length) {
        ret = ret.add(objs.shift());
    }
    return ret;
};

$.merge([h3, btn]).hide()


$.map can flatten arrays:

function merge(array_of_jquery_objects) {
    return $($.map(array_of_jquery_objects, function(el) {
        return el.get();
    }));
}


$(btn).add(h3).hide();

Not sure if it works though, documentation for add doesn't mention haivng the jQuery object as a parameter but only a list of elements, so if that doesn't work this should:

$(btn).add(h3.get()).hide();


Get some jQuery objects:

var x = $('script'),
    y = $('b'),
    z = $('body');

Create a new jQuery object, containing all the other objects:

$( $.map([x,y,z], a => [...a]) )

Demo: (open your browser's console)

var x = $('script'),
    y = $('b'),
    z = $('body');

// step 1
// put all the jQuery objects in an Array to prepare for step 2
var step1 = [x,y,z];
console.log(step1)

// using jQuery.map and a callback, extract  the actual selector from the iterable 
// array item and return it, so the result would be a simple array of DOM nodes
// http://jqapi.com/#p=jQuery.map
var step2 = $.map(step1, a => [...$.makeArray(a)])
console.log(step2);

// convert the javascript Array into jQuery Object (which contains all the nodes)
var step3 = $( step2 )
console.log(step3);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
<b></b>


Use this one.

<script>

var btn = $('button')[0];
var h3 = $('h3')[0];

$([btn,h3]).hide();

</script>


To take the use of add a little farther, you could use reduce with it for another approach:

var $mySelector1 = $('.selector1');
var $mySelector2 = $('.selector2');
var $mySelector3 = $('.selector3');
var selectorArray = [$mySelector1,$mySelector2,$mySelector3];
var $combinedSelector = selectorArray.reduce(function(total, current){
    return $(total).add(current)
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜