views:

71

answers:

4
            var a=$('#start > div:last-child');
            var b=$('#start > div.live')[0];
            alert(a==b)
            alert(a==$(b))

it always false,

how to compare two element in jquery,

thanks

A: 

The collection results you get back from a jQuery collection do not support set-based comparison. You can use compare the individual members one by one though, there are no utilities for this that I know of in jQuery.

Frank Schwieterman
+7  A: 

You could compare DOM elements. Remember that jQuery selectors return arrays which will never be equal in the sense of reference equality.

Assuming:

<div id="a" class="a"></div>

this:

$('div.a')[0] == $('div#a')[0]

returns true.

Darin Dimitrov
Have you tested this? I'm pretty sure it won't return true because of the differences in the `.selector` property.
Will Morgan
Yes, I've tested this code on IE6, FF 3.6 and Chrome 4. It returns `true` on all these browsers.
Darin Dimitrov
A: 

Random AirCoded example of testing "set equality" in jQuery:

$.fn.isEqual = function($otherSet) {
  if (this === $otherSet) return true;
  if (this.length != $otherSet.length) return false;
  var ret = true;
  this.each(function(idx) { 
    if (this !== $otherSet[idx]) {
       ret = false; return false;
    }
  });
  return ret;
};

var a=$('#start > div:last-child');
var b=$('#start > div.live')[0];

console.log($(b).isEqual(a));
gnarf
A: 

Every time you call the jQuery() function, a new object is created and returned. So even equality checks on the same selectors will fail.

<div id="a">test</div>

$('#a') == $('#a') // false

The resulting jQuery object contains an array of matching elements, which are basically native DOM objects like HTMLDivElement that always refer to the same object, so you should check those for equality using the array index as Darin suggested.

$('#a')[0] == $('#a')[0] // true
Anurag