3

The code below alerts false

var a = $('html'); 
var b = $('html'); 
alert(a==b);

Is there a way to know if two variables are pointing to the same element?

Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171
  • Two separate jQuery instances will never be equal. You could compare `a[0] == b[0]`, but in general you'd want to check the length of each jQuery instance and then the list of elements one by one. – Pointy Jul 10 '16 at 16:12
  • 1
    Check [jQuery object equality](http://stackoverflow.com/questions/3176962/jquery-object-equality) – Mohammad Jul 10 '16 at 16:22

2 Answers2

3

Using the normal equality operators (ie. == and ===) doesn't work for objects. However, you can use the is() method to compare two jQuery objects, like this:

var $a = $('html'); 
var $b = $('html'); 

if ($a.is($b)) {
  console.log('same')
} else {
  console.log('not the same');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • Thanks a lot. I knew `.is` and have used it a lot like `is(':checked')`. but didn't know it can be used like this. – Ashkan Mobayen Khiabani Jul 10 '16 at 16:16
  • 1
    Note that `is()` checks if *at least one of* the elements in the first collection ***is in*** the second collection, the two collections can be completely different. – adeneo Jul 10 '16 at 16:26
0

Use the javascript isSameNode() method. reference

var a = $('html'); 
var b = $('html'); 
alert(a[0].isSameNode(b[0]));

The [0] indexer of a jquery object returns the native DOM object

Catalin
  • 11,503
  • 19
  • 74
  • 147