JQuery add () method strange behavior
I have two identical (?) Pieces of code:
var x = document.createElement('div');
var y = document.createElement('div');
var z = $().add(x).add(y);
console.log(z);
and
var x = document.createElement('div');
var y = document.createElement('div');
var z = $();
z.add(x);
z.add(y);
console.log(z);
The first example shows me: + Object [div, div]
And other: Object []
Why???
Fiddle: http://jsfiddle.net/d3x7gsLu/
More magic: http://jsfiddle.net/d3x7gsLu/1/
UPD:
First correct answer: StackOverflow question.
Now my question is:
And how to do it (add elements to the internal collection) without creating a new jQuery object? Because in reality I have many, many elements.
UPD2:
The answer is here: Aggregating jQuery object?
Thanks for all!
source to share
From the jQuery API :
Given a jQuery object, which is a collection of DOM elements, the .add () method creates a new jQuery object from the concatenation of those elements and the ones passed to the method. The argument for .add () can be almost anything that $ () accepts, including a jQuery selector expression, DOM element references, or HTML fragment.
This means your examples are not equal and your second example should look like this:
var x = document.createElement('div');
var y = document.createElement('div');
var z = $();
z = z.add(x);
z = z.add(y);
console.log(z);
source to share
$.add()
returns a new value, it does not change the original value z
. In the first example, you say:
Create an empty jQuery object, add an element to a variable
x
to it then add an element to a variabley
to it. Assign this object to a variablez
.
After that, the value z
will be an object containing two elements.
In the second example, you say:
Create an empty jQuery object. Assign this object to a variable
z
. Then see what happens if you add an item to a variablex
to that object. Then see what happens if you add an item to a variabley
to that object.
After that, the value z
is still the original empty object.
To make example 2 like example 1, you would need to update your code like this:
var x = document.createElement('div');
var y = document.createElement('div');
var z = $();
z=z.add(x);
z=z.add(y);
console.log(z);
As you can see, the value is being z
updated.
source to share