treecoder
treecoder

Reputation: 45091

Adding multiple jQuery/DOM elements to single jQuery object

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.

Upvotes: 11

Views: 5450

Answers (3)

treecoder
treecoder

Reputation: 45091

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.

Upvotes: 15

Jai
Jai

Reputation: 74738

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/

Upvotes: 1

charlietfl
charlietfl

Reputation: 171669

Loop over array using each:

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

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

Upvotes: 2

Related Questions