4

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?

2
  • jQuery uses the syntax you used for arrays of DOM elements already. It's probably possible to make a plugin that would allow that syntax, but that would be confusing. Best to either use .add() or make a plug-in that uses .add() to hide the syntax. It should be hard to make a $.fromArray() plugin. Commented Jun 15, 2012 at 12:38
  • 1
    Check this jsfiddle.net/joycse06/cGMd9 Commented Jun 15, 2012 at 12:54

2 Answers 2

3

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')) 

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

Comments

1

You are missing : in your code. Write it as -

a = $('div:eq(0)'); 

Use jQuery.merge() http://api.jquery.com/jQuery.merge/

or jQuery.map() http://api.jquery.com/jQuery.map/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.