jQuery object equality jQuery object equality jquery jquery

jQuery object equality


Since jQuery 1.6, you can use .is. Below is the answer from over a year ago...

var a = $('#foo');var b = a;if (a.is(b)) {    // the same object!}

If you want to see if two variables are actually the same object, eg:

var a = $('#foo');var b = a;

...then you can check their unique IDs. Every time you create a new jQuery object it gets an id.

if ($.data(a) == $.data(b)) {    // the same object!}

Though, the same could be achieved with a simple a === b, the above might at least show the next developer exactly what you're testing for.

In any case, that's probably not what you're after. If you wanted to check if two different jQuery objects contain the same set of elements, the you could use this:

$.fn.equals = function(compareTo) {  if (!compareTo || this.length != compareTo.length) {    return false;  }  for (var i = 0; i < this.length; ++i) {    if (this[i] !== compareTo[i]) {      return false;    }  }  return true;};

Source

var a = $('p');var b = $('p');if (a.equals(b)) {    // same set}


If you still don't know, you can get back the original object by:

alert($("#deviceTypeRoot")[0] == $("#deviceTypeRoot")[0]); //Truealert($("#deviceTypeRoot")[0] === $("#deviceTypeRoot")[0]);//True

because $("#deviceTypeRoot") also returns an array of objects which the selector has selected.


The $.fn.equals(...) solution is probably the cleanest and most elegant one.

I have tried something quick and dirty like this:

JSON.stringify(a) == JSON.stringify(b)

It is probably expensive, but the comfortable thing is that it is implicitly recursive, while the elegant solution is not.

Just my 2 cents.