5

I like to have a return value with one or more jQuery objects to add them to a .

var f = function() { var a = $('<div class="a" />'); // do someting awesome return a; }; 

Correct example with two s:

var f = function() { var ret = $('<div class="a" /><div class="b" />'); // do something spectecular return ret; }; 

The problem is that I need these two objects separated inside the function and this is not correct code:

var f = function() { var a = $('<div class="a" />'), b = $('<div class="b" />'), ret = a+b; // do something fabulous return ret; } 
1
  • why not just do $('div.a, div.b').each(function() {. inside the each function, $(this) refer to the current jquery object Commented Mar 28, 2013 at 11:10

3 Answers 3

13

You can use the jQuery .add() method:

return a.add(b); 

From the docs:

Given a jQuery object that represents a set of DOM elements, the .add() method constructs a new jQuery object from the union of those elements and the ones passed into the method.

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

3 Comments

damn shit. thats too easy - i just didn't find this method :)
@iRaS - Yup, very easy! The jQuery docs is a good place to start... I would recommend you spend an hour or so reading through them.
you are absolutely right. I read a lot in the documentation. It's the last way to post a question. But I thought it's an object with array structured items so I tried extend() and merge() and read the documentation about read and merge. That doesn't helped me and there is no reference to add()..
0

I just found a solution for my own question:

var f = function() { var a = $('<div class="a" />'), b = $('<div class="b" />'), ret = $.extend({}, a); ret.push(b[0]); // do something fabulous return ret; } 

Maybe you have better solutions? It doesn't look very well you know.

Comments

0

Check this out:

var $bindDivs = $.merge( $( '#div1' ), $( '#div2' ) ); 

3 Comments

Please explain your answer
@Mazz I really think it's pretty straightforward. I'm just using the jQuery.merge to unificate the two objects in one. I've tested it and it works pretty well. I use it myself.
Nonetheless you should always explain your answers

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.