Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does `$(document) === $(document)` returns false in jQuery? [duplicate]

I tried $(document) === $(document) but found the result is false..

Does anyone have ideas about this?

like image 748
Hanfei Sun Avatar asked Dec 25 '14 07:12

Hanfei Sun


4 Answers

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
like image 137
Zudwa Avatar answered Nov 17 '22 23:11

Zudwa


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
like image 22
Or Duan Avatar answered Nov 17 '22 23:11

Or Duan


Reference Link

You can check equality of two object using is() function like

alert($(document).is($(document)));  // return true

JS Fiddle

like image 7
Sadikhasan Avatar answered Nov 17 '22 23:11

Sadikhasan


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.

like image 5
PaulDapolito Avatar answered Nov 18 '22 00:11

PaulDapolito