jQuery object equality

EqualityJquery

Equality Problem Overview


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

Equality Solutions


Solution 1 - 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
}

Solution 2 - Equality

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.

Solution 3 - Equality

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.

Solution 4 - Equality

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.

Solution 5 - Equality

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

Solution 6 - Equality

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

Solution 7 - Equality

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCasebashView Question on Stackoverflow
Solution 1 - EqualitynickfView Answer on Stackoverflow
Solution 2 - EqualitymaurisView Answer on Stackoverflow
Solution 3 - EqualityRoberto PierpaoliView Answer on Stackoverflow
Solution 4 - EqualityElf KingView Answer on Stackoverflow
Solution 5 - EqualityRemo H. JansenView Answer on Stackoverflow
Solution 6 - EqualityKareemView Answer on Stackoverflow
Solution 7 - EqualityVikramView Answer on Stackoverflow