Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging jQuery objects

Tags:

jquery

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.

like image 946
David Hellsing Avatar asked Dec 10 '09 15:12

David Hellsing


People also ask

How to merge 2 arrays in jQuery?

The jQuery merge() method together merges the content of two arrays into the first array. This method returns the merged array. The merge() method forms an array containing the elements of both arrays. If we require the first array, we should copy it before calling the merge() method.

How to join array in jQuery?

Its a javascript function. The join() method joins the elements of an array into a string, and returns the string. The elements will be separated by a specified separator.

How do you combine objects in JavaScript?

The easiest way to merge two objects in JavaScript is with the ES6 spread syntax / operator ( ... ). All you have to do is insert one object into another object along with the spread syntax and any object you use the spread syntax on will be merged into the parent object.


2 Answers

.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.add(objs.shift());     }     return ret; };  $.merge([h3, btn]).hide() 
like image 138
nickf Avatar answered Oct 08 '22 13:10

nickf


$.map can flatten arrays:

function merge(array_of_jquery_objects) {     return $($.map(array_of_jquery_objects, function(el) {         return el.get();     })); } 
like image 35
Tgr Avatar answered Oct 08 '22 13:10

Tgr