I tried $(document) === $(document)
but found the result is false
..
Does anyone have ideas about this?
Because on top of jQuery, every call ($()
or jQuery()
) to it returns new instance:
return new jQuery.fn.init( selector, context );
So all jQuery instances (Even for same selectors) are always different (E.g. $("#id") === $("#id")//false
)
You can check source code (Line 78) of jQuery 2.1.0
But if you put it to variable, you can achieve an equality:
var d, d_copy;
d = $(document);
d_copy = d;
d_copy === d; //true
When you use jQuery you get a JS object back. This object is totally different every time you use the jQuery selector.
To understand this better, I played in the console with some arrays:
a = [1, 2]
[1,2]
b = [1, 2]
[1,2]
a == b
false
a === b
false
When using jQuery it's just like using objects, because you don't get a DOM element in response (maybe that why you got confused)
How Can You Do It?
If you do want to compare 2 jQuery objects you could use the is() jQuery method:
$(document).is($(document))
true
Reference Link
You can check equality of two object using is() function like
alert($(document).is($(document))); // return true
JS Fiddle
Each time you select the document
element using jQuery, you are given a new selection of that element encapsulated in a jQuery object.
Thus, the first call to $(document)
selects the document
element in the DOM and gives you a new instance of a jQuery object which holds that selection. The second selection hands you yet another instance of a jQuery object encapsulating the same document
element. While these jQuery objects do indeed have identical data members, they are two distinct objects encapsulating the document
DOM element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With