163

How do I determine if two jQuery objects are equal? I would like to be able to search an array for a particular jQuery object.

$.inArray(jqobj, my_array);//-1    
alert($("#deviceTypeRoot") == $("#deviceTypeRoot"));//False
alert($("#deviceTypeRoot") === $("#deviceTypeRoot"));//False
Casebash
  • 114,675
  • 90
  • 247
  • 350

7 Answers7

246

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
}
Liam
  • 27,717
  • 28
  • 128
  • 190
nickf
  • 537,072
  • 198
  • 649
  • 721
  • 1
    This solution simplifies to that given by [thephpdeveloper](http://stackoverflow.com/questions/3176962/jquery-object-equality/3176971#3176971) when there is only a single element. Another sense in which jQuery objects can be considered equal is whether they have the same selector and context. This is easy enough to test: `A.selector === B.selector && A.context === B.context`. Often the context will always be the same, so we only have to consider the selector. – Casebash Jul 05 '10 at 04:55
  • 2
    @Casebash - true, however consider that several selectors could end up with the same result set, eg: `$(':first')` and `$('*:first')` – nickf Jul 05 '10 at 08:07
  • 3
    Caution @rampion and nickf, jQuery **is() does not check that selectors are identical**, merely that they overlap. Witness: http://jsfiddle.net/bnhkm/1/ – Bob Stein Jul 28 '13 at 17:57
  • your `equals` function seems to be order-sensitive. something like http://stackoverflow.com/a/29648479 would work in more cases, although it's slower. – Jayen Dec 26 '15 at 01:57
  • the equals function only works if the object has one level! comparing a=b = [{dir: 'test', sort: [{test: {test:1} }] }] does not work – DavidDunham May 03 '16 at 12:02
  • 1
    The question is about jquery objects, not objects in general. – nickf May 03 '16 at 12:13
17

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

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

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

mauris
  • 42,982
  • 15
  • 99
  • 131
15

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.

Liam
  • 27,717
  • 28
  • 128
  • 190
  • 1
    that's not good for checking equality between two jQuery objects but for standard objects. like "{a:'x',b:'y',c:'z'} == {a:'x',b:'y',c:'z'}". i'm wondering that there is no jQuery.isEqual(a, b)... – iRaS Apr 04 '13 at 06:44
  • 16
    This is wrong. Order of the object properties matters. So if you have `{a: 1, b: 2}` and `{b: 2, a: 1}` this will return `false` when it should return `true`. – Eric Alberson May 12 '14 at 19:41
  • 3
    @EricAlberson, do you have any suggestions on other deep compare tools or scripts that could handle this situation? – Neil Monroe Aug 13 '14 at 19:14
8

It is, generally speaking, a bad idea to compare $(foo) with $(foo) as that is functionally equivalent to the following comparison:

<html>
<head>
<script language='javascript'>
    function foo(bar) {
        return ({ "object": bar });
    }

    $ = foo;

    if ( $("a") == $("a") ) {
        alert ("JS engine screw-up");
    }
    else {
        alert ("Expected result");
    }

</script>

</head>
</html>

Of course you would never expect "JS engine screw-up". I use "$" just to make it clear what jQuery is doing.

Whenever you call $("#foo") you are actually doing a jQuery("#foo") which returns a new object. So comparing them and expecting same object is not correct.

However what you CAN do may be is something like:

<html>
<head>
<script language='javascript'>
    function foo(bar) {
        return ({ "object": bar });
    }

    $ = foo;

    if ( $("a").object == $("a").object ) {
        alert ("Yep! Now it works");
    }
    else {
        alert ("This should not happen");
    }

</script>

</head>
</html>

So really you should perhaps compare the ID elements of the jQuery objects in your real program so something like

... 
$(someIdSelector).attr("id") == $(someOtherIdSelector).attr("id")

is more appropriate.

Elf King
  • 1,189
  • 5
  • 7
  • 1
    Just to be clear, jQuery doesn't have an object attribute. Elf King seems to be using this as pseudocode – Casebash Jul 05 '10 at 03:09
5

First order your object based on key using this function

function sortObject(o) {
    return Object.keys(o).sort().reduce((r, k) => (r[k] = o[k], r), {});
}

Then, compare the stringified version of your object, using this funtion

function isEqualObject(a,b){
    return JSON.stringify(sortObject(a)) == JSON.stringify(sortObject(b));
}

Here is an example

Assuming objects keys are ordered differently and are of the same values

var obj1 = {"hello":"hi","world":"earth"}
var obj2 = {"world":"earth","hello":"hi"}

isEqualObject(obj1,obj2);//returns true
Kareem
  • 5,068
  • 44
  • 38
4

Use Underscore.js isEqual method http://underscorejs.org/#isEqual

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Remo H. Jansen
  • 23,172
  • 11
  • 70
  • 93
-1

If you want to check contents are equal or not then just use JSON.stringify(obj)

Eg - var a ={key:val};

var b ={key:val};

JSON.stringify(a) == JSON.stringify(b) -----> If contents are same you gets true.

Vikram
  • 179
  • 1
  • 7