Ashkan Mobayen Khiabani Ashkan Mobayen Khiabani - 4 months ago 11
jQuery Question

How to know if two jquery objects are pointing to the same element

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?

Answer

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>

Comments