Reputation: 11896
I need to wrap up an array of elements into a jQuery object as if they were selected so that I can call various jQuery actions on them.
I'm looking for a function like foo
below that accepts an array of elements and returns a jQuery object with them in it.
var elements = [element1, element2, element3];
$(foo(elements)).click(function() {
...
});
Can someone shed some light on this?
Thanks much.
Upvotes: 4
Views: 13714
Reputation: 42808
Use each to iterate over both objects and arrays
var elements = ['element1', 'element1', 'elements3'];
$.each(elements, function(index, value) {
alert(index + ': ' + value);
});
Check working example at http://jsfiddle.net/LpZue/
Upvotes: 2
Reputation: 195962
Just do
$(elements).click( function(){ ... });
if your elements are actual references to the DOM
demo: http://jsfiddle.net/gaby/dVKEP/
Upvotes: 7
Reputation:
Use jQuery.each
Example:
$.each(elements, function(index, element) {
$(element).doStuff();
});
Upvotes: 4