tags:

views:

512

answers:

5

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>

<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.

A: 

You could always write a selector that accepts both:

$('button, h3').hide();
David Hedlund
Yes I know, but that's not the question... I need to merge already existing DOM objects into one, similar to what your example would return.
David
+2  A: 

You could use the add method.

kgiannakakis
Yes, like this: $.fn.add.call(btn,h3);
David
A: 

$('h3,button') returns one jQuery collection, and should be suffcient.

Sveisvei
Did you read the question?
David
Obviously not good enough,tho` now I got learned.
Sveisvei
+1  A: 
$(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 it that doesn't work this should:

$(btn).add(h3.get()).hide();
svinto
+1  A: 

.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.add(objs.shift());
    }
    return ret;
};

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