4

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.

4
  • How are you selecting the elements for elements in the first place? Commented Feb 21, 2011 at 3:01
  • Are the elements in the array existing jQuery wrapped elements or normal DOM references? Commented Feb 21, 2011 at 3:03
  • @Daniel I have a table of elements, and I need to select all elements under one column which have the same name format. For example, all form elements that represent a location would have a name in the format foo*.bar*.location, where * is an index. I wasn't sure how to select them, so I was going to do document.getElementById() in a for loop since I know the number of rows. Commented Feb 21, 2011 at 3:10
  • @alex They are DOM references. Commented Feb 21, 2011 at 3:10

3 Answers 3

7

Just do

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

if your elements are actual references to the DOM

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

Sign up to request clarification or add additional context in comments.

2 Comments

Note that it processes them in the order in which they appear in the array - which is nice if such a thing is important.
Like he said, it's only if they are references to the dom. Your fiddle works with jquery selectors. Kinda makes sense when you think about it. You wouldn't write $($("#id")) to select an element.
4

Use jQuery.each

Example:

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

Comments

2

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.