Tom Tucker
Tom Tucker

Reputation: 11896

Select an array of elements in jQuery

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

Answers (3)

Hussein
Hussein

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

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195962

Just do

$(elements).click( function(){ ... });

if your elements are actual references to the DOM

demo: http://jsfiddle.net/gaby/dVKEP/

Upvotes: 7

user479911
user479911

Reputation:

Use jQuery.each

Example:

$.each(elements, function(index, element) { 
    $(element).doStuff();
});

Upvotes: 4

Related Questions