34

I'm inside a function and I need to return a jQuery object with two elements. Inside the function I have, for example:

function getInput() {
    $hiddenInput = $('<input type="hidden">');
    //(other code)
    $select = $('<select></select>');
    //(other code)
    $hiddenInput.add($select);
    return $hiddenInput;
}

And outside I have:

$myContainer.append(getInput());

The result expected would be:

<div id="container"><input type="hidden"><select></select></div>

But the only thing I get right now with .add() is only the input element and not the select. How can I joint those two form elements on the function return? If not possible with jQuery, then with plain JavaScript. Thanks a lot.

3 Answers 3

55

add() creates (and returns) a new jQuery object that is the union of the original set and what you're adding to it, but you're still returning the original in your function. You seem to have wanted to do this instead:

function getInput() {
    $hiddenInput = $('<input type="hidden">');
    //(other code)
    $select = $('<select></select>');
    //(other code)
    return $hiddenInput.add($select);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Oh my, that's in the docs. I had not read well. Thanks a lot!
Jquery documentation says the sort order is undefined in this case.
in short, we say .add() is non-destructive
5

You can use

$hiddenInput.after($select);

That will put the $select after the $hiddenInput, achieving what you want to get.

4 Comments

Conversely you could use: $select.insertAfter($hiddenInput);
That didn't worked either. I only get the input element without the select, like with add().
It may be that none of the elements is in the DOM yet?
You're still returning $hiddenInput afterwards, yes?
2

You can use the following:

this.MergejQueryObjects = function(arrayOfJqueryObjects) {
        return $($.map(arrayOfJqueryObjects, function (el) {
            return el.get();
        }));
    }

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.