jQuery equals
playing with jQuery recently, we were in need to compare equality of some jQuery objects. it looks quite weird to find this not to be part of the API.
i finally found what is needed:
| Javascript | | copy | | ? |
$.fn.equals = function(compareTo) { |
if (!compareTo || !compareTo.length || this.length!=compareTo.length) |
{ |
return false; |
} |
for (var i=0; i<this .length; i++) { |
if (this[i]!==compareTo[i]) { |
return false; |
} |
} |
return true; |
} |


Or, to put it another way, you “just” compare each DOM element of the jQuery objects. Do we agree ?
If so, it raises the question of why does the DOM elements order matter… Indeed, the way the equality is checked the DOM elements of both jQuery objects have to be in the same order if I’m getting it right…
++
well, going through the array on DOM elements is reasonable due to the fact, that i could be used on jquery objects that represent more than one dom element like:
(“.foo”).equals(“.bar”)
in fact, comparing two lists, i´d assume the order of them to be part of the comparison. in other words: if i have two lists (aka as collections having an order) in – let´s say java – i´d say they aren´t equal just because they contain the same elements but in different order.
I totally agree from the “object” perspective. However, I don’t see much use cases where this order would matter (rather the other way in fact). Makes me wonder how the order is defined and how to “reset” it… :$
Anyway, I’m glad to see that us going at the DOM elements behind the jQuery objects wasn’t utterly wrong
++
it is a javascript array, isn´t it ?
http://www.javascriptkit.com/javatutors/arraysort.shtml
I had stuff to do so I couldn’t look by myself, thanks a lot ! I’m now back to drinking… It’s better than it sounds, I insist
see ya !