qwertymk qwertymk - 1 month ago 8
Javascript Question

combine jQuery Objects


Possible Duplicate:

Merging jQuery objects




See Demo



a = $('div:eq(0)');
b = $('div:eq(1)');
c = $('div:eq(2)');
d = $('div:eq(3)');
e = $('div:eq(4)');
f = $('div:eq(5)');

console.log($([a,b,c,d,e,f]).find('a'))




What I'm trying to do is add multiple jQuery objects to a single set.

I know I can add them one at a time by using
.add()
but I'm looking for a way to turn an array of jQuery objects into a single jQuery set.

Is there any way to do this?

Answer

Not possible in plain jQuery, as the syntax is already used for DOM elements.

But a simple plugin will do the job just fine:

http://jsfiddle.net/gMDjZ/

a = $('div:eq(0)');
b = $('div:eq(1)');
c = $('div:eq(2)');
d = $('div:eq(3)');
e = $('div:eq(4)');
f = $('div:eq(5)');

jQuery.fromArray = function(a) {
    var c = jQuery();
    for(x in a) {
        c = c.add(a[x]);            
    }       
    return c;
}

console.log($.fromArray([a,b,c,d,e,f]).find('a'))