13

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

Does anyone have ideas about this?

Salman A
  • 262,204
  • 82
  • 430
  • 521
Hanfei Sun
  • 45,281
  • 39
  • 129
  • 237

4 Answers4

19

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
Zudwa
  • 1,360
  • 10
  • 13
17

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
jbkkd
  • 1,510
  • 5
  • 18
  • 37
Or Duan
  • 13,142
  • 6
  • 60
  • 65
7

Reference Link

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

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

JS Fiddle

Community
  • 1
  • 1
Sadikhasan
  • 18,365
  • 21
  • 80
  • 122
5

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.

PaulDapolito
  • 824
  • 6
  • 12