11

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.

3
  • what are $el1 $el2 and $el3? Dom elements previously chosen by jQuery? Commented Dec 16, 2012 at 14:54
  • 1
    Why don't you push them in an array? Commented Dec 16, 2012 at 14:55
  • And how do I make a jQuery object out of that array (elegantly) Commented Dec 16, 2012 at 14:56

3 Answers 3

15

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.

Sign up to request clarification or add additional context in comments.

1 Comment

jquery failed me here
2

Loop over array using each:

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

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

Comments

1

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/

1 Comment

so what do you want adding same text in every div

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.