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
Use Underscore.js isEqual method http://underscorejs.org/#isEqual
If you still don't know, you can get back the original object by:
because
$("#deviceTypeRoot")
also returns an array of objects which the selector has selected.Since jQuery 1.6, you can use
.is
. Below is the answer from over a year ago...If you want to see if two variables are actually the same object, eg:
...then you can check their unique IDs. Every time you create a new jQuery object it gets an id.
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:
Source
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.
It is, generally speaking, a bad idea to compare $(foo) with $(foo) as that is functionally equivalent to the following comparison:
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:
So really you should perhaps compare the ID elements of the jQuery objects in your real program so something like
is more appropriate.
The
$.fn.equals(...)
solution is probably the cleanest and most elegant one.I have tried something quick and dirty like this:
It is probably expensive, but the comfortable thing is that it is implicitly recursive, while the elegant solution is not.
Just my 2 cents.