74

Is it possible to merge several jQuery DOM objects into one array and call jQuery methods on all of them?

F.ex:

<button>one</button>
<h3>two</h3>

<script>

var btn = $('button');
var h3 = $('h3');

$([btn,h3]).hide();

</script>

This doesn't work. I know I can use the 'button,h3' selector here but in some cases I already have several jQuery DOM elements and I need to merge them so I can call jQuery prototypes on all of them.

something like:

$.merge([btn,h3]).hide();

would work. Any ideas?

UPDATE:

Solved it. You can do it like this:

$.fn.add.call(btn,h3);

I'm going to accept the add() suggestion as for pointing me in the right direction.

8
  • 5
    @David, why the bizarre use of call? btn.add(h3) works... Commented Dec 10, 2009 at 15:53
  • 1
    Because I do not know the first object, so I can't chain. Apply() would be even better, so I can send an array using $.fn.add.apply(arr.shift(),arr); Commented Dec 10, 2009 at 16:21
  • 1
    is there a way to add more than 2 objects ? Commented Mar 31, 2010 at 7:41
  • 12
    If you don't know the first object, you can avoid using call by chaining off an empty jQuery object: $().add(btn).add(h3). IMO, this is a much better way to use $.add. Commented Aug 19, 2010 at 18:58
  • 1
    is this basically a duplicate of stackoverflow.com/questions/323955/… Commented Aug 28, 2014 at 21:43

6 Answers 6

34

.add() does exactly what you're after.

h3.add(btn).hide();

If you wanted to make it a little more convenient for yourself, with a "merge" function like in your question, this could be added easily:

$.merge = function(objs) {
    var ret = objs.shift();
    while (objs.length) {
        ret = ret.add(objs.shift());
    }
    return ret;
};

$.merge([h3, btn]).hide()
Sign up to request clarification or add additional context in comments.

2 Comments

JQuery now has a merge function so something other than $.merge should be used.
If I'm not mistaken, jQuery.Add method causes a new jQuery object to be produced instead of modifying the original object on which the method is called. Isn't it ret = ret.Add(objs.shift());?
8

$.map can flatten arrays:

function merge(array_of_jquery_objects) {
    return $($.map(array_of_jquery_objects, function(el) {
        return el.get();
    }));
}

1 Comment

Useful when you're stuck with an old jQuery version (< 1.3.2).
6
$(btn).add(h3).hide();

Not sure if it works though, documentation for add doesn't mention haivng the jQuery object as a parameter but only a list of elements, so if that doesn't work this should:

$(btn).add(h3.get()).hide();

1 Comment

Not sure which version was active in 2009, but 1.3.2 added the add(selector : jQuery) overload.
3

Get some jQuery objects:

var x = $('script'),
    y = $('b'),
    z = $('body');

Create a new jQuery object, containing all the other objects:

$( $.map([x,y,z], a => [...a]) )

Demo: (open your browser's console)

var x = $('script'),
    y = $('b'),
    z = $('body');

// step 1
// put all the jQuery objects in an Array to prepare for step 2
var step1 = [x,y,z];
console.log(step1)

// using jQuery.map and a callback, extract  the actual selector from the iterable 
// array item and return it, so the result would be a simple array of DOM nodes
// http://jqapi.com/#p=jQuery.map
var step2 = $.map(step1, a => [...$.makeArray(a)])
console.log(step2);

// convert the javascript Array into jQuery Object (which contains all the nodes)
var step3 = $( step2 )
console.log(step3);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
<b></b>

1 Comment

Can you add an explanation about your solutions, please?
2

To take the use of add a little farther, you could use reduce with it for another approach:

var $mySelector1 = $('.selector1');
var $mySelector2 = $('.selector2');
var $mySelector3 = $('.selector3');
var selectorArray = [$mySelector1,$mySelector2,$mySelector3];
var $combinedSelector = selectorArray.reduce(function(total, current){
    return $(total).add(current)
});

Comments

1

Use this one.

<script>

var btn = $('button')[0];
var h3 = $('h3')[0];

$([btn,h3]).hide();

</script>

1 Comment

This will only merge the very first element in each set, therefor it is far from an optimal answer. only good in very specific cases.

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.