Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding multiple jQuery/DOM elements to single jQuery object

Tags:

jquery

I have references to multiple divs and I want to add them all to ONE jQuery object at once.

These things don't work...

>>> $( $e1, $e2, $e3 )
[div]

>>> $([ $e1, $e2, $e3 ])
[[div], [div], [div]]

>>> $().add($e1, $e2, $e3)
[div]

>>> $().add([ $e1, $e2, $e3 ])
[[div], [div], [div]]

However this works:

>>> $().add($e1).add($e2).add($e3)
[div, div, div]

>>> $e1.add($e2).add($e3)
[div, div, div]

But I want more elegant solution.

like image 982
treecoder Avatar asked Dec 16 '12 14:12

treecoder


3 Answers

jQuery does allow you to add a bunch of elements at once to a jquery object, but only when those elements are pure DOM elements, not jquery objects themselves.

var $e1 = $('#x'),
    $e2 = $('#y'),
    $e3 = $('#z');

var e1 = $e1[0],
    e2 = $e2[0],
    e3 = $e3[0];


>>> $( [$el, $e2, $e3] )    // does not work
[[div], [div], [div]]       // jquery object that contains other jQuery objects

>>> $( [el, e2, e3] )       // works
[div, div, div]             // jquery object that contains pure DOM objects

When we pass an array of jquery objects to jQuery(), they are NOT "unwrapped" before adding them to the result jquery object.

Also remember, however, that passing a single jquery object makes the unwrapping happen.

>>> $( $e1 )
[div]                       // returns a jquery object

Interestingly, if we mix jquery and pure DOM objects, only the pure objects are operated upon:

>>> $( [$e1, e2, $e3] ).css('background-color', '#000');

Note above that second element is a pure DOM element and the background color is only applied to that second element.

The bottom line is: if you want to add multiple elements to a jquery object at once, add pure DOM object, not jquery objects.

like image 67
treecoder Avatar answered Nov 09 '22 19:11

treecoder


Loop over array using each:

$.each([ $e1, $e2, $e3 ], function(i, $el){
    $el.doSomething()
})

DEMO: http://jsfiddle.net/REXmh/

like image 36
charlietfl Avatar answered Nov 09 '22 19:11

charlietfl


Well you have to make array of these objects and push that into a variable.

var $a = $('<div/>').attr('class','box');
var $b = $('<div/>').attr('class','box');
var $c = $('<div/>').attr('class','box');
var $d = $('<div/>').attr('class','box');

var $arr = [$a, $b, $c, $d];

$.each($arr, function(i, el){
  $(el).text('asdf').appendTo('body');
});

plz checkout the fiddle:

http://jsfiddle.net/nvRVG/1/

like image 27
Jai Avatar answered Nov 09 '22 17:11

Jai