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;
} 

5 comments to jQuery equals

  • Joseph Pachod

    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…

    ++

  • Uwe Schaefer

    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.

  • Joseph Pachod

    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 ;)

    ++

  • Joseph Pachod

    :)

    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 !

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>